Luigi
Luigi

Reputation: 5603

ruby if X is not equal to Y or Z then

I have the following:

a_disposition = [nil,'test','demo']

a_volume = a_disposition.count{|x| x != nil}

I want to count all values that are NOT nil and NOT 'test'. What is the ruby way of saying count where x is not nil and x is not 'test'? I am using ruby 2.0.

Upvotes: 1

Views: 680

Answers (4)

hirolau
hirolau

Reputation: 13921

I think using the count method with a block is the cleanest way:

a_disposition.count{|x| !x.nil? && x != 'test'}

Upvotes: 0

alup
alup

Reputation: 2981

a_disposition.compact.reject{ |x| x == 'test' }.count

Upvotes: 0

Matt
Matt

Reputation: 20796

(a_disposition-[nil,'test']).count # => 1

Upvotes: 6

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

Another approach. It's not super performant, but it has nice functional touch. :)

a_disposition = [nil,'test','demo']

a_volume = a_disposition.reject(&:nil?).reject{|d| d == 'test'}.count # => 1

Upvotes: 0

Related Questions