红宝石:访问数组
为什么我不能做到以下几点:红宝石:访问数组
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]}"
奥马哈[0]行工作,但CURRENT_LOCATION [1]没有。我怀疑这是因为omaha是一个字符串,而我的puts是为该字母返回一个ASCII码(这实际上是发生了什么)。
我该如何解决这个问题?
你想获得这样的:
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]
真的吗?
这个完美的作品。谢谢! –
这是非常脏和坏的设计 – fl00r
@NoahClark:这是非常好的机会,这不是真的想要你想要的,特别是如果'current_location'实际上充满了用户输入。 –
您正在运行的是哪个版本的Ruby?我刚刚在1.9中试过,它返回的不是ASCII参考。
我正在使用1.8.x –
@fl00r解决了它,但使用RVM进行测试,在我的机器上显示您正在尝试的操作确实会返回一个ASCII字符,它可能已在发行版中进行了调整。 –
这也许是一个更好的解决方案:
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]}"
这是非常相似的http://*.com/questions/7113208/how-to-store-and-retrieve-values-using-ruby/7113366#comment-8521962 –
类似于您的代码级别最简单的办法,到目前为止是使用:
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]}"
但由于克努特上面显示,这将是更好地将产品制作成结构或对象而不是散列中的标签。然后,他在关于散列的声明中继续展示如何为这些产品设置默认值。
你期望什么? – fl00r
我需要能够采取我的current_location和访问基于该值的数组。 –
'current_location [1]'应该返回'omaha [1]'??? – fl00r