我想在ruby中使用哈希时尝试获取默认值.查找文档,您使用了一个fetch方法.因此,如果未输入哈希,则默认为值.这是我的代码.
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
Run Code Online (Sandbox Code Playgroud)
Car*_*and 14
你有几个选择.@dinjas提到了一个,可能是你想要使用的那个.假设您的哈希是
h = { :a=>1 }
Run Code Online (Sandbox Code Playgroud)
然后
h[:a] #=> 1
h[:b] #=> nil
Run Code Online (Sandbox Code Playgroud)
假设默认值是4.然后就像dinjas所说,你可以写
h.fetch(:a, 4) #=> 1
h.fetch(:b, 4) #=> 4
Run Code Online (Sandbox Code Playgroud)
但其他选择是
h.fetch(:a) rescue 4 #=> 1
h.fetch(:b) rescue 4 #=> 4
Run Code Online (Sandbox Code Playgroud)
要么
h[:a] || 4 #=> 1
h[:b] || 4 #=> 4
Run Code Online (Sandbox Code Playgroud)
您还可以使用Hash#default =将默认值构建到哈希本身:
h.default = 4
h[:a] #=> 1
h[:b] #=> 4
Run Code Online (Sandbox Code Playgroud)
或者像这样定义哈希:
g = Hash.new(4).merge(h)
g[:a] #=> 1
g[:b] #=> 4
Run Code Online (Sandbox Code Playgroud)
din*_*jas 10
你只需要给fetch它一个可以处理的默认值.january由于您没有声明具有该名称的任何变量,因此它不知道该怎么做.如果要将默认值设置为字符串"january",则只需要像这样引用它:
cohort.fetch(:cohort, "january")
Run Code Online (Sandbox Code Playgroud)
文档中fetch有一些不错的例子.
另外,cohort是不是Hash,这是一个String自gets.chomp回报String.fetch用于从a中"获取"值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
Run Code Online (Sandbox Code Playgroud)
希望这很有帮助.
| 归档时间: |
|
| 查看次数: |
7854 次 |
| 最近记录: |