Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short way to write `{|x| x}`?

Tags:

ruby

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.

like image 735
sawa Avatar asked Jun 05 '13 06:06

sawa


People also ask

What is IE stand for?

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.

What eg stand for?

for example. Hint: The abbreviation e.g. is short for the Latin phrase exempli gratia, meaning "for example."

Is it IE or eg 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.


2 Answers

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 
like image 124
Boris Stitnicky Avatar answered Sep 17 '22 02:09

Boris Stitnicky


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.

like image 45
charleyc Avatar answered Sep 18 '22 02:09

charleyc