4

In JS, inner functions could be quite handy to simplify the code, something like:

function complexStuff() {
  function step1() { ... }
  function step2() { ... } 

  step1()
  step2()
}

Is it possible to use something similar in Ruby, or are there different approaches?

I don't like private methods because private methods are available to the whole class, and in this case, I want to limit the scope of the inner function even more--to just one method.

sawa
  • 165,429
  • 45
  • 277
  • 381
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

4

A Ruby lambda is similar to an anonymous js function:

step1 = lambda {puts "I am a lambda!"}
step1.call "optional args", ...

Some shorthand:

f = -> {puts "Shorthand lambda"}
f.()

More info (including shorthand notation!!) here

ContinuousLoad
  • 4,692
  • 1
  • 14
  • 19
  • Lambda also let you do things like `array.map(&some_lambda)` which helps clean up and clarify chains of Enumerable method calls. – mu is too short Aug 13 '17 at 04:05