Ruby:访问数组

时间:2011-08-18 19:10:18

标签: ruby arrays string

为什么我不能执行以下操作:

current_location = 'omaha'
omaha = []

omaha[0] = rand(10)
omaha[1] = rand(10) + 25
omaha[2] = rand(5) + 10

puts "You are currently in #{current_location}."
puts "Fish is worth #{omaha[0]}"
puts "Coal is worth #{current_location[1]}"
puts "Cattle is worth #{current_location[2]}"

omaha [0]行有效,但current_location [1]没有。我怀疑是因为奥马哈是一个字符串而我的看台正在返回该字母的ASCII码(事实上正是这样)。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

也许这是一个更好的解决方案:

LOCDATA = Struct.new(:fish, :coal, :cattle)
location_values = Hash.new{ |hash, key| hash[key] = LOCDATA.new(rand(10), rand(10) + 25, rand(5) + 10) }

current_location = 'omaha'

puts "You are currently in #{current_location}"
puts "Fish is worth #{location_values[current_location].fish}"
puts "Coal is worth #{location_values[current_location].coal}"
puts "Cattle is worth #{location_values[current_location].cattle}"

#You may also use:
puts "Fish is worth #{location_values[current_location][0]}"

答案 1 :(得分:1)

你想得到这个:

current_location = 'omaha'
omaha = []
omaha[0] = rand(10)
omaha[1] = rand(10) + 25
omaha[2] = rand(5) + 10
eval("#{current_location}[1]")
# the same as:
omaha[1]

真的?

答案 2 :(得分:1)

您运行的是哪个版本的Ruby?我刚刚在1.9中尝试了这个,它返回的字母不是ASCII参考。

答案 3 :(得分:1)

到目前为止,类似于您的代码级别的最简单的解决方案是使用:

locations = {}              #hash to store all locations in

locations['omaha'] = {}     #each named location contains a hash of products
locations['omaha'][:fish] = rand(10)
locations['omaha'][:coal] = rand(10) + 25
locations['omaha'][:cattle] = rand(5) + 10


puts "You are currently in #{current_location}"
puts "Fish is worth #{locations[current_location][:fish]}"
puts "Coal is worth #{locations[current_location][:coal]}"
puts "Cattle is worth #{locations[current_location][:cattle]}"

但正如上面所示的knut,最好将产品变成结构或对象,而不仅仅是散列中的标签。然后他继续展示如何在关于哈希的声明中为这些产品制作默认值。