2011-08-18 236 views
0

爲什麼我不能做到以下幾點:紅寶石:訪問數組

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碼(這實際上是發生了什麼)。

我該如何解決這個問題?

+0

你期望什麼? – fl00r

+0

我需要能夠採取我的current_location和訪問基於該值的數組。 –

+0

'current_location [1]'應該返回'omaha [1]'??? – fl00r

回答

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] 

真的嗎?

+0

這個完美的作品。謝謝! –

+3

這是非常髒和壞的設計 – fl00r

+1

@NoahClark:這是非常好的機會,這不是真的想要你想要的,特別是如果'current_location'實際上充滿了用戶輸入。 –

1

您正在運行的是哪個版本的Ruby?我剛剛在1.9中試過,它返回的不是ASCII參考。

+0

我正在使用1.8.x –

+0

@fl00r解決了它,但使用RVM進行測試,在我的機器上顯示您正在嘗試的操作確實會返回一個ASCII字符,它可能已在發行版中進行了調整。 –

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

這是非常相似的http://stackoverflow.com/questions/7113208/how-to-store-and-retrieve-values-using-ruby/7113366#comment-8521962 –

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

但由於克努特上面顯示,這將是更好地將產品製作成結構或對象而不是散列中的標籤。然後,他在關於散列的聲明中繼續展示如何爲這些產品設置默認值。