Reputation: 23
I am trying to use a parameter as my key to find the value in a hash, and I just confused about why I couldn't get the value by the first way. I am new to Ruby.
def getCards(player,hash)
a =$player
puts "a = "+a.to_s
puts "a.class = "+a.class.to_s
puts " hash[:a]"+" #{hash[:a]}"
puts " hash[:'1']"+" #{hash[:"1"]}"
end
edit:
def getCards(player,hash)
puts player
#result successfully 1 or any number that I gets from console
puts hash[player]
# nothing but 1 is actually a key in my hash
# {1=>["yellow3", "yellow8", "green9", "black11", "red1", "black7", "red5", #"yellow7", more results ..
end
Upvotes: 2
Views: 565
Reputation: 211540
Note that Ruby is not PHP or Perl, so that should be player
and not $player
. Argument names and their corresponding use as variables are identical.
$player
refers to the global variable of that name, which is unrelated and will be presumed to be undefined unless otherwise set.
Now if by hash[:a]
you mean to access the contents of the hash under the key with the player value you've assigned to a
then what you actually want is:
hash[player]
Where that represents looking up an entry with that key. a
is a variable in this case, :a
is the symbol "a" which is just a constant, like a label, which has no relation to the variable.
Don't forget that "#{x}"
is equivalent to x.to_s
so just use interpolation instead of this awkward "..." + x.to_s
concatenation.
Another thing to keep in mind is that in Ruby case has significant meaning. Variable and method names should follow the get_cards
style. Classes are ClassName
and constants are like CONSTANT_NAME
.
Upvotes: 3