Ruby: Accessing An Array
Why can't I do the following:
开发者_开发技巧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]}"
The omaha[0] line works, but the current_location[1] doesn't. I suspect it is because omaha is a string and my puts is returning an ASCII code for that letter (That is in fact what is happening).
How do I get around this?
Perhaps this is a better solution:
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]}"
You want to get this:
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]
Really?
Which version of Ruby are you running? I've just tried this in 1.9 and it returns the letter not an ASCII reference.
The simplest solution similar to your level of code so far would be to use :
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]}"
But as knut showed above, it would be better to make the products into a struct or object instead of just labels in a hash. He then went on to show how to make the default values for those products, in the statement about the hash.
精彩评论