Murrr... why can't we use do...end here?
double = do |x| x * 2 end
But I think do...end and {...} should be synonyms. Two intuitions
disagree - so think again.
Ok, if behaves like a method, just that is has no name, we should look
at method definition syntax rather than block syntax.
def double x
x * 2
end
double = def x
x * 2
end
double = def x; x * 2; end
double = def(x) x * 2; end
matz said "def is not sufficient since we don't define anything here".
So what about do:
double = do x
x * 2
end
double = do x; x * 2; end
double = do(x) x * 2 end
double = do(x = 1, **a) x * 2 end
This is illegal in Ruby 1.8, so it shouldn't break code.
Surely I forgot something, but to me it looks nice, because
- it looks like def
- it looks like block
- it is not used so far (I hope)
- it is short (enougth; you don't use lambda so much)
- it is readable (in my eyes)
I'm basically with Daniel Brockman, my version of his counter:
make_counter = do(start=0) do start += 1 end end
counter = make_counter[5]
5.times { puts counter.call }
(Even if I don't understand why you need this; 0.counter would be
cooler. I don't use lambdas much, maybe because I'm grown with Pascal.)
Now, the optic / syntax check:
do(a, b) a + b end.call
{1: do(a, b) puts "Hello World" end}
do(bar: do(a, b) a * b end, qux: do(str) str.reverse end)
funs = [do(a, b) a - b end, do(a, b) a + b end]
funs = [
# compare length, noise, rubyness...
->(a, b) { a - b },
fun(a, b) { a - b },
do(a, b) a + b end,
]
# This one looks like Ruby, I think
def adder a
do b
a + b
end
end
adder = do a do b # greetings from Haskell?
a + b
end end # ok, this is not Haskell
search_fun = do x: 0, y: 0, width: @width, height: @height, type:
Types.All, limit: @objects.size, skip: 0, destructive: false,
&block
block ||= do object; true end
# etc.
end
Sad thing: Without parameters, it look strange:
now = do() Time.now end
now = do; Time.now end
now = do
Time.now
end
This is the same with methods; and we usually give a method >= 3 lines.
We should do with lambdas, too, if we really think of them as anonymous
methods; and you can always trade \n for ; if you are a one liner guy.