Is there a { |x| x } shorthand in ruby?
ruby
Solution
If you do not care about what is returned you can sometimes use the `hash` method.
Thw feature you are asking for is not available in Ruby yet, however. it is present in the Ruby road-map:
https://bugs.ruby-lang.org/issues/6373
Expected to be implemented before 2035-12-25, can you wait?
That being said, how much typing is `group_by{|x|x}` ?
Edit:
As Stefan pointed out, my answer is now longer valid for Ruby 2.2 and above since the introduction of `Object#itself`.
Problem
I often use `.group_by{ |x| x }` and `.find{ |x| x }` The latter is to find the first item in an array which is true. Currently I'm just using `.compact.first` but I feel like there must be an elegant way to use find here, like `find(&:to_bool)` or `.find(true)` that I'm missing. Using `.find(&:nil?)` works but is the opposite of what I want, and I couldn't find a method that was the opposite of #find or #detect, or a method like #true? So is there a more elegant way to write `.find{ |x| x }`? If not, I'll stick with `.compact.first` (I know compact won't remove `false` but that's not a problem for me, also please avoid rails methods for this) Edit: For my exact case it is used on arrays of only strings and nils e.g. `[nil, "x", nil, nil, nil, nil, "y", nil, nil, nil, nil]` => `"x"`