Ruby // 使用输入从哈希中选择和传输项目
Ruby // Selecting and Transferring items from hashes using Input
我正在使用 Ruby 制作一个基本的 CLI 网络 scraper。系统将询问用户他们希望查看哪个股票指数。他们的输入将被视为:
$input = gets.chomp.downcase.to_s
我有一个散列用作临时数据库。我知道,这不是最佳实践,但这是我仅使用 Ruby 个对象就想到的最好的方法。
示例哈希:
index_info_resource = {
"dax" => {
full_name: "Deutscher Aktienindex (German stock index)",
exchange: "Frankfurt Stock Exchange"
web_site: "investing.com/dax/test
},
"fchi" => {
full_name: "Cotation Assistée en Continu",
exchange: "Euronext Paris"
web_site: "investing.com/fchi/test
}
}
因为会有一个 scraper class,信息将来自那里以及来自这个数据库哈希,我正在考虑制作一个暂存哈希:@@requested_index = Hash.new
然后我会在其中添加我需要的信息,如下所示:
@@requested_index[:full_name] = index_info_resource["#{"dax"}"][:full_name]
当我以这种方式使用用户输入时,我的问题是:
@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]
我收到这个错误:
undefined method `[]' for nil:NilClass (NoMethodError)
我不确定为什么或如何解决这个问题。如果我只使用相同的字符串,它就可以工作。如果用户输入的是同一个字符串,则不会。
谢谢你的时间。
您的 $input
已经是一个字符串,因此在这种情况下您不需要字符串插值。此外 "#{"$input"}"
将计算为 "$input"
而不是该变量的值。
改变一下
@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]
到
@@requested_index[:exchange] = index_info_resource[$input][:full_name]
我正在使用 Ruby 制作一个基本的 CLI 网络 scraper。系统将询问用户他们希望查看哪个股票指数。他们的输入将被视为:
$input = gets.chomp.downcase.to_s
我有一个散列用作临时数据库。我知道,这不是最佳实践,但这是我仅使用 Ruby 个对象就想到的最好的方法。
示例哈希:
index_info_resource = {
"dax" => {
full_name: "Deutscher Aktienindex (German stock index)",
exchange: "Frankfurt Stock Exchange"
web_site: "investing.com/dax/test
},
"fchi" => {
full_name: "Cotation Assistée en Continu",
exchange: "Euronext Paris"
web_site: "investing.com/fchi/test
}
}
因为会有一个 scraper class,信息将来自那里以及来自这个数据库哈希,我正在考虑制作一个暂存哈希:@@requested_index = Hash.new
然后我会在其中添加我需要的信息,如下所示:
@@requested_index[:full_name] = index_info_resource["#{"dax"}"][:full_name]
当我以这种方式使用用户输入时,我的问题是:
@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]
我收到这个错误:
undefined method `[]' for nil:NilClass (NoMethodError)
我不确定为什么或如何解决这个问题。如果我只使用相同的字符串,它就可以工作。如果用户输入的是同一个字符串,则不会。
谢谢你的时间。
您的 $input
已经是一个字符串,因此在这种情况下您不需要字符串插值。此外 "#{"$input"}"
将计算为 "$input"
而不是该变量的值。
改变一下
@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]
到
@@requested_index[:exchange] = index_info_resource[$input][:full_name]