In the thread “Should this work?”, I proposed that :collect should be able
to operate without an explicit block parameter. For example:
[“john”, “mary”].map { |name| name.capitalize }
CAN BE EXPRESSED AS
[“john”, “mary”].map { $_.capitalize } # -> [“john”, “mary”]
[1, 2, 3, 4].map { |i| i ** 2 } # -> [1, 4, 9, 16]
CAN BE EXPRESSED AS
[1, 2, 3, 4].map { $_ ** 2 } # -> [1, 4, 9, 16]
Guy Decoux pointed out that the blocks are independent of the method calling
them, so the above could only be done by allowing implicit assignment of the
local variable $_ in every “do … end” block.
Is this agreeable?
I would usually continue to name my parameters explicitly, just to make it
clear what’s being operated on (useful in a dynaically typed language!).
However, the motivation for my proposal is very simple cases like the
following:
input = ARGV.map { |s| s.to_i }
And, of course, this whole discussion was prompted by such constructs as:
[x, y, z].each { |arr| arr << nil }
[x, z, z].map { |arr| arr == [nil] }
The above three examples would be more concisely written as:
input = ARGV.map { $_.to_i }
[x, y, z].each { $_ << nil }
[x, y, z].map { $_ == [nil] }
Whether this terseness is useful is for discussion.
Cheers,
Gavin
···
–
Gavin Sinclair Software Engineer
Sydney, Australia Soyabean Software Pty Ltd