Well, you do it the same way: write an anymous lambda literal, and immediately call it.
There is one caveat, though: Ruby does not have variable declarations. So, any use of a variable name inside a block which also exists outside the block refers to the captured outside variable, whereas in ECMAScript, if you declare var foo
within a function, it will shadow the outside variable foo
.
If you want the same behavior in Ruby, you have to explicitly declare foo
as a block-local variable in the block's parameter list:
-> (;foo) do
foo = 'bar'
puts 'hi!'
end.()
If you don't do that, the assignment inside the block is going to modify a captured outside binding. Compare:
foo = 'foo'
-> do
foo = 'bar'
puts 'hi!'
end.()
foo
# => 'bar'
As you can see, the outside binding is modified.
foo = 'foo'
-> (;foo) do
foo = 'bar'
puts 'hi!'
end.()
foo
# => 'foo'
As you can see, only the second one actually matches the ECMAScript version:
"use strict";
const foo = 'foo';
(() => {
const foo = 'bar';
console.log('hi!');
})()
foo
// => 'foo'
->{ foo = "bar" }.call
looks more ruby like imho. – Interstratify