Where can I find an explanation of what the "=>
" operator means in Ruby?
Let me give more detail. If you have this:
class Acct < ActiveRecord::Base
validates_confirmation_of :password, :email_address, :on => :create
end
What is the '=>' operator doing in this case? Thanks
-
The symbol "=>" is not an operator. It's just a syntactic means to express that there is a relationship of "key-value" between the other two elements. It's used to define hashes (or associative arrays, as they're called in some other languages, eg. PHP). In this sense, because "=>" it's not an operator, it doesn't do anything (so as symbols "[" and "]" don't do anything when used to define an array). If you are still confused, have a look into the Hash Ruby class and compare it to the Array class.
jleedev : Confusingly, the {braces} to define a hash are optional when it's passed to a method, which makes it look like keyword arguments, as in this example: """def f(x) x end; f :a => :b, :c => :d""" #=> {:c=>:d, :a=>:b} -
To expand on the accepted answer (it's not an operator), think of it basically in the same way as a comma.
{ "foo" => "bar", "a" => "b" }
The comma separates each pair in the hash, the
=>
separates the key and the value inside the pair.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.