What does -> mean in Ruby

<>

This question already has an answer here:

Answers


It is a lambda literal. Check this example:

 > plus_one = ->(x){x+1}
 => #<Proc:0x9fbaa00@(irb):3 (lambda)> 
 > plus_one.call(3)
 => 4 

A lambda literal is a constructor for Proc. A Proc is a way to have a block of code assigned to a variable. After this, you can call your block of code again, with different arguments, as many times as you wish.

This is how you can pass a "function" as parameter in ruby. In many languages, you could pass a reference to a function. In ruby, you can pass a Proc object.


In Ruby 1.9 you can use the stab operator -> to create a lambda.

l1 = lambda { puts "I'm a lambda" }
l2 = -> { puts "I'm a lambda" } 

The operator also accept arguments.

l1 = lambda(name) { puts "I'm a #{name}" }
l2 = ->(name) { puts "I'm a #{name}" } 

Need Your Help

Invalid fingerprint for generating Google Map key for android application

android android-layout android-mapview

I have successfully generated the fingerprint Certificate for google map key by using these command

Single query to update records with different values based column value in oracle

sql oracle

I need to update a column person_id in a table based on the other column family_id. Multiple records can contain for each family id. I want to set person_id values starting with 1 and increment by ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.