1

In JavaScript I can do something like that:

var foo = function(){
  var a = 5;
  a = a*a;
  return a;
}();

So I can define anonymous function I will use only once. I was trying but my approach is wrong:

foo = {
  a = 5
  a = a*a
  return a
}
#=> SyntaxError: unexpected '\n'...

foo = do
  a = 5
  a = a*a
  a
end
#=> SyntaxError: unexpected keyword_do_block...

foo = {
  a = 5
  a = a*a
  a
}()
#=> SyntaxError: unexpected '\n'...
Stefan
  • 109,145
  • 14
  • 143
  • 218
WBAR
  • 4,924
  • 7
  • 47
  • 81

1 Answers1

5

Well, you could use in Ruby lambda

foo = ->(a) { a * a }
foo.call(4) # => 16

Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.

Read this When to use lambda, when to use Proc.new?.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317