gpt4 book ai didi

ruby - 如何在 ruby​​ 中使用哈希值获取默认值

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:03 26 4
gpt4 key购买 nike

我试图在 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

最佳答案

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

cohort.fetch(:cohort, "january") 

documentation for fetch 中有一些不错的例子.

此外,cohort 不是Hash,它是一个String,因为gets.chomp 返回一个字符串fetch 用于从 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

希望对您有所帮助。

关于ruby - 如何在 ruby​​ 中使用哈希值获取默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com