Ruby: доступ к массиву - PullRequest
       7

Ruby: доступ к массиву

0 голосов
/ 18 августа 2011

Почему я не могу сделать следующее:

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] - нет.Я подозреваю, что это потому, что omaha - это строка, и мои путы возвращают код ASCII для этой буквы (на самом деле это и происходит).

Как мне обойти это?

Ответы [ 4 ]

3 голосов
/ 18 августа 2011

Возможно, это лучшее решение:

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 голос
/ 19 августа 2011

Самое простое решение, похожее на ваш уровень кода, до сих пор было бы использовать:

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]}"

Но, как показал кнут, было бы лучше превратить продукты в структуру или объект, а не просто в метки в хэше. Затем он показал, как сделать значения по умолчанию для этих продуктов, в заявлении о хэше.

1 голос
/ 18 августа 2011

Какую версию Ruby вы используете?Я только что попробовал это в 1.9, и он возвращает письмо, а не ссылку ASCII.

1 голос
/ 18 августа 2011

Вы хотите получить это:

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]

Действительно

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...