Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "equals greater than" operator => in Ruby?

In a Ruby on Rails tutorial, I am asked to type:

class Post < ActiveRecord::Base
    validates :name,  :presence => true  
    validates :title, :presence => true, :length => { :minimum => 5 }
end

I understand what this does, but I would like to know what the => operator is. In PHP-land, it links a key and a value in an associative array. Is it the same thing here? Is it a Ruby operator or a Rails operator?

like image 573
MM. Avatar asked Jun 18 '11 04:06

MM.


People also ask

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What is the difference between || and or in Ruby?

The: or operator has a lower precedence than || . or has a lower precedence than the = assignment operator. and and or have the same precedence, while && has a higher precedence than || .

What is ||= in Ruby?

a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.


1 Answers

It is mainly a ruby operator that sets the value of a key inside a hash. Thus :

{ :minimum => 5 }

Is a ruby hash that has the symbol :minimum as a key that maps to the value of 5. A hash with one entry, in this example. Same for :

:presence => true

Still a hash. However, in ruby, when you have a method, you can omit the {} that surround a hash. That is what happens with the validates method. It's a method and thus the passed hash does not explicitly need {}.

like image 111
Spyros Avatar answered Sep 25 '22 15:09

Spyros