Tutorial :Ruby => operator [duplicate]


This question already has an answer here:

Where can I find an explanation of what the => operator means in Ruby?

For example,

class Acct < ActiveRecord::Base    validates_confirmation_of :password, :email_address, :on => :create  end  

what is the => operator doing in this case?


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.


The "Hash Rocket" Syntax

The symbol is not an operator, just part of the syntax that is used to define a literal Hash object. It is often called a hash rocket.

Normally, a literal hash object would be defined something like this:

a = { :x => 1, :y => 2 } # same thing as: a = Hash.new; a[:x] = 1; a[:y] = 2  

It could be passed to a method, of course:

def f(x); end; f({:x => 1, :y => 2})  

As it happens, when a hash is passed as the last parameter to a method, the {} part of the object literal can be dropped:

f(:x => 1, :y => 2)  

The parens are also optional, so we get things like:

f :x => 1:, :y => 2 # and of course...  validates_confirmation_of :password, :email_address, :on => :create  

Finally (in modern Ruby only) for the specific case where the hash key is a symbol, you can write key : value, so:

f x: 1, y: 2 # not to mention...  validates_confirmation_of :password, :email_address, on: :create  

Note here that method calls can be made within class definitions. They get executed like any other method call, but at the time of the definition. They are particularly useful for a package like Rails that does lots of metaprogramming to extend the language and the library objects for its application domain.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »