We often shorten a block using the &
notation on a symbol like this:
some_array.group_by(&:foo)
Is there a similar way to shorten expressions like {|x| x}
?
some_array.group_by{|x| x}
If there were a method Object#self
that returns self
, then we can do
some_array.group_by(&:self)
but unfortunately, there is no such method. In terms of the number of characters, it may be longer, but readability improves.
I.e. stands for the Latin id est, or 'that is,' and is used to introduce a word or phrase that restates what has been said previously.
for example. Hint: The abbreviation e.g. is short for the Latin phrase exempli gratia, meaning "for example."
I.e. stands for id est or 'that is' — and is used to clarify the statement before it. E.g. means exempli gratia or 'for example. ' It's used to introduce examples and illustrate a statement. Both i.e. and e.g. are abbreviations for Latin expressions.
Yes. #itself
was implemented in Ruby 2.2.0.
You can access the Ruby core team discussion about this feature here.
As an interesting analogue, the #ergo
method has been proposed, which would yield the receiver to a given block.
If you haven't yet upgraded to Ruby 2.2.0, you may wish to backport #itself
and/or define #ergo
as follows:
class Object def itself; self end def ergo fail ArgumentError, "Block expected!" unless block_given? yield self end end
And then:
some_array.group_by &:itself
Well, there's no built-in as far as I know, but you can make a reusable identity block:
id = Proc.new {|x| x} some_array.group_by(&id)
And then if you really wish this were a language feature:
class Object def it Proc.new {|x| x} end end
And then you can do:
some_array.group_by(&it)
wherever you like. This may void your warranty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With