Does {| x | x} reduction in ruby?

I often use .group_by{ |x| x }and.find{ |x| x }

The latter should find the first element in the array, which is true.
Currently I just use it .compact.first, but I feel that there should be an elegant way to use it here, for example, find(&:to_bool)or .find(true)that I am missing.
Usage .find(&:nil?)works, but the opposite of what I want, and I could not find a method opposite #find or #detect, or a method like #true?

So, is there a more elegant way to write .find{ |x| x }? If not, I will stick .compact.first
(I know that compact will not remove false, but that is 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 niles, for example
[nil, "x", nil, nil, nil, nil, "y", nil, nil, nil, nil]=>"x"

+4
source share
6 answers

If you don't care about what returns, you can sometimes use the method hash.

The Thw function you request is not yet available in Ruby. it is present on the route map of Ruby:

https://bugs.ruby-lang.org/issues/6373

It is expected to be completed until 2035-12-25, can you wait?

At the same time, how much is printed group_by{|x|x}?

Edit:

As Stefan noted, my answer is now longer for Ruby 2.2 and up since the introduction Object#itself.

+2
source

No.

If it tapworked without a block, which you could do:

array.detect(&:tap)

. , , , , , , , , :

array.compact.first

, , Ruby, , , "".

, array.detect { |x| !x } (), :

array.detect(&:!)

, !x x.!. , nil false, , , .

+2

, . , .

IDENTITIY = -> x { x }

.group_by(&IDENTITY)

Object#itself self:

.group_by(&:itself)
+1

, Enumerable#detect, :

array.detect { |x| x }

, monkeypatch:

class ::Object
  def not_pure?
    !!self
  end
end

array.detect &:not_pure?
0

ruby - Rails (, ActiveSupport) presence, , present? ( , , , ..):

array.find(&:presence)

, , .

0

group_by, map, select, sort_by -. , :

class Hash
  def method_missing(n)
    if has_key? n
      self[n]
    else
      raise NoMethodError
    end
  end
end

, ruby, , jsonified by as_json, , . :

# make yellow cells
yellow = red = false
tube_steps_status.group_by(&:step_ordinal).each do |type|
    group = type.last.select(&:completed).sort_by(&:completed)
    red = true if group.last.step_status == 'red' if group.any?
    yellow = true if group.map(&:step_status).include?('red')
end
tube_summary_status = 'yellow' if yellow unless red
0

Source: https://habr.com/ru/post/1524223/


All Articles