Key-Value Ruby method declaration [closed]-Collection of common programming errors
And how do I access the Key and value for this method? Is there a good resource to answer these types of questions? Ruby syntax is a little strange to me.
Well yes, the Ruby syntax is strange when you don’t acknowledge it, but fun and powerful once mastered. Ruby has a very concise and possibly confusing syntax for hashes and arrays.
For example an array would be normally generated by the following syntax:
x = [1, 2, 3]
but you can shorten it up to:
x = 1, 2, 3
In your case while generally that method can be called as:
a.method( { "hello" => "bye" } )
it can also be called as you defined in your question’s code. The fact is that in that case there’s not ambiguity, as two String
s paired with a =>
can only mean that you are producing an Hash
.
This means that to reproduce it you can just create a method that accepts an hash and deals with the values:
def method( hash )
# hash.keys.first is how you can access the key ( "hello" )
# hash.first is how you can access the value ( "bye" )
end
Now, you have to keep in mind that with the method above, anyone using it might also pass multiple values (more than one) or even a non hash parameter, that you either choose to ignore or deal with, like in the following example:
def method( hash )
raise ArgumentError "..." unless hash.is_a? Enumerable
raise ArgumentError "..." if hash.size > 1
# ...
end
In the first line you raise an exception if the hash cannot be enumerated (like Hash
es do). In the second one you check for the number of key-values in the hash and raise an exception if it is more than one.
The final thing to notice is that you cannot take more than one argument out for that method and expect it to work with that syntax:
def method( hash, a ); end
method( "hello" => "bye", 1 )
# => SyntaxError: syntax error, unexpected ')'
even though, it can be resolved by using:
method( { "hello" => "bye" }, 1 )
Have fun.