2016-09-17 88 views
0

我想在ruby中使用哈希时获得默认值。查看使用获取方法的文档。所以如果没有输入散列,那么它默认为一个值。这是我的代码。如何在ruby中使用哈希获取默认值

def input_students 
    puts "Please enter the names and hobbies of the students plus country of birth" 
    puts "To finish, just hit return three times" 

    #create the empty array 
    students = [] 
    hobbies = [] 
    country = [] 
    cohort = [] 

    # Get the first name 
    name = gets.chomp 
    hobbies = gets.chomp 
    country = gets.chomp 
    cohort = gets.chomp 

    while !name.empty? && !hobbies.empty? && !country.empty? && cohort.fetch(:cohort, january) do #This is to do with entering twice 
    students << {name: name, hobbies: hobbies, country: country, cohort: cohort} #import part of the code. 
    puts "Now we have #{students.count} students" 

    # get another name from the user 
    name = gets.chomp 
    hobbies = gets.chomp 
    country = gets.chomp 
    cohort = gets.chomp 
    end 
    students 
end 
+0

downvote可能是因为你还没有提出你的问题。您需要编辑问题以清楚地说明问题。 –

+0

考虑在选择答案之前等待更长的时间(至少几个小时,也许)。快速选择可能会阻止其他答案,并将仍在解答问题的答案短路。没有急于。您仍然需要编辑您的问题,因为很多成员可能会在将来阅读您的问题(并且还会阻止更多的降低投票)。 –

回答

2

你只需要给fetch默认它可以处理。它不知道如何处理january,因为您尚未用该名称声明任何变量。如果您想为默认值设置为字符串"january",那么你只需要引用这样的:

cohort.fetch(:cohort, "january") 

里有documentation for fetch一些体面的例子。

另外,cohort不是Hash,它是String,因为gets.chomp返回Stringfetch用于从Hash中“提取”值。你使用它的方式应该是抛出类似于:undefined method 'fetch' for "whatever text you entered":String的错误。

最后,由于您在条件中使用它,因此您致电fetch的结果正在评估其真实性。如果您设置了默认值,它将始终评估为true

如果你只是想设置默认为cohort,如果它是空的,你可以做这样的事情:

cohort = gets.chomp 
cohort = "january" if cohort.empty? 
while !name.empty? && !hobbies.empty? && !country.empty? 
    students << { 
    name: name, 
    hobbies: hobbies, 
    country: country, 
    cohort: cohort 
    } 
    ... # do more stuff 

希望这是有帮助的。

+0

所以我快到了。刚刚必须让一个字符串。 – AltBrian

+0

现在我得到这个错误'coderunner.rb:16:in input_students':未定义的方法'获取'为“”:String(NoMethodError)'。 – AltBrian

+0

查看我上面的扩展答案。 – dinjas

5

你有几个选择。 @dinjas提到了一个,可能是你想使用的那个。假设你的散列

h = { :a=>1 } 

然后

h[:a] #=> 1 
h[:b] #=> nil 

假设默认为4。然后,随着dinjas建议,你可以写

h.fetch(:a, 4) #=> 1 
h.fetch(:b, 4) #=> 4 

但其他选项

h.fetch(:a) rescue 4 #=> 1 
h.fetch(:b) rescue 4 #=> 4 

h[:a] || 4 #=> 1 
h[:b] || 4 #=> 4 

你也可以创建默认进入哈希本身,用Hash#default=

h.default = 4 
h[:a] #=> 1 
h[:b] #=> 4 

或通过定义散列像这样:

h = Hash.new(4).merge({ :a=>1 }) 
h[:a] #=> 1 
h[:b] #=> 4 

参见Hash::new

+2

也可以使用['Hash#default_proc'](http://ruby-doc.org/core-2.1.5/Hash.html#method-i-default_proc-3D)根据某些条件返回值。 – mudasobwa

+0

@mudasobwa,好点。读者,一个常见的例子是'h.default_proc = - >(h,k){h [k] = []}',所以如果写'h [k] << 3'并且'h'没有键'k','h [k]'被设置为等于一个空数组,然后'3'被添加到该数组。这也可以写成'h = Hash.new {| h,k | h [k] = []} .merge()'。 –