0

I want a method to return true when all the elements of an array are equal and are "yes". I have one array ["yes", "yes", "yes"]. All its elements are the same "yes". I want it to return true. For ["no", "no", "no"], although all the elements are "no", the value is not equal to "yes". How can I do that?

I am using this method to check this:

def self.all_equal?(array) array.max == array.min end 

but it returns true for ["no", "no", "no"].

1
  • Cannot be reproduced. Your code is not even syntactically valid. Commented Apr 14, 2016 at 7:58

5 Answers 5

5

This should solve your problem:

def self.all_equal?(array) array.uniq == ['yes'] end 
Sign up to request clarification or add additional context in comments.

1 Comment

This incorrectly returns false for an empty array. But the question was not necessarily clear on that.
4
def self.all_equal_to_yes? array array.all? { |x| x == "yes" } end 

Note that this will return true for the empty array. If you want it to return false in that case, use FixerRB's answer. I also used the name all_equal_to_yes? since that makes what the method is doing much more explicit than just all_equal?. You could also define a more general method:

def self.all_equal_to?(array, value) array.all? { |x| x == value end 

And then be able to call it like so:

$ Foo.all_equal_to? ["no", "no", "no"], "yes" #=> false $ Foo.all_equal_to? ["no", "no", "no"], "no" #=> true 

(Replace Foo with whatever class you're defining this method on)

2 Comments

You should delete both your answer to the question that was not asked and your remark about having initially misread the question. That's all excess baggage.
I can agree with that. I'll leave the naming note though, I wouldn't consider that excess baggage, since the poor naming is what led me to misunderstand the question (well, that and the poor original title before sawa fixed it).
2

I know this was a couple of years ago, but I stumbled upon this question and thought I'd share something I recently learned:

value = "yes" array.all?(value) #=> returns true 

so then you'd be changing the value input as you like.

Comments

1
["yes", "yes", "yes"].grep_v("yes").empty? # => true ["no", "yes", "yes"] .grep_v("yes").empty? # => false ["no", "no", "no"] .grep_v("yes").empty? # => false 

Comments

0

The current method just checks if all the elements of an array are equal. If you want to also check that they are all equal to "yes", you'll need to add an explicit check for this. Since they are all equal, it's sufficient to check that one of them is indeed "yes":

def self.all_equal?(array) array.max == array.min && array[0] == "yes" end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.