2

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
1
  • hash["1"] returns a result that I need , however why I can not use a variable as a parameter key to get the value? Commented Oct 9, 2017 at 15:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for your answer, but why I can not assign a =$player?
You can do that, but it doesn't mean anything here since $player is nil and completely unrelated to the player argument. Just because it's valid Ruby code doesn't mean it works as you expect.
def getCards(player,hash) puts player // result 1 puts hash[player] result nil end
I gave player = 1 , and puts 1 successfully ,buy why hash[player] returns nil? and player.class = string
Thanks tadman , I solved the problem by changed the type of my key ,I used int as my key and it works fine by puts hash[players.to_i] and player is a parameter that was sent previously .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.