Vivek
Vivek

Reputation: 621

'DRY'ing up my Ruby Syntax

I have a repeated comparison in which I have to check whether three variables equal a certain variable. For simplicity, I'll create a scenario that illustrates the problem that I am having.

if time == -1 and day_of_week == -1 and month == -1 

I was wondering if there is a terse, logically-equivalent way of achieving this same line of code without the repetition.

Right now I'm using a roundabout way of doing this as follows:

all_equal = true
[time_now, day_of_week, month].each { |value| all_equal = false if value != -1 }
if all_equal ....

Hah, obviously it's pretty over the top (and clearly less efficient) but I find the lack of repetition more pleasing to look at.

Would you recommend a better approach to this?

Thank you!

Upvotes: 3

Views: 66

Answers (1)

Platinum Azure
Platinum Azure

Reputation: 46193

Use Enumerable#all?:

if [time_now, day_of_week, month].all? { |value| value == -1 }
  # do something
end

Upvotes: 6

Related Questions