3

I have to compare multiple variables and check if they are different. Is there any smooth way to do this? I can do

var1 = 3
var2 = "test"
var3 = 100

if var1 != var2 && var1 != var3 && var2 != var3
  ...
end

But if the list of variables are getting longer, this becomes unhandy. I thought about something like var1 != var2 != var3 but that doesn't work. So maybe there is a simple Ruby-way to do this.

3
  • with your philosophy var1 != var2 != var3 do you want to continue if var1 != var2 is true for var3 also? or vice-versa? Apr 12, 2013 at 7:57
  • 1
    Equality is transitive but inequality is not transitive.
    – sawa
    Apr 12, 2013 at 8:03
  • @sawa is right, even if a chained notation existed, var1 != var2 != var3 would be a shorthand for var1 != var2 && var2 != var3, it wouldn't ensure that var1 != var3, thus "failing" for 3 != 5 != 3.
    – Stefan
    Apr 12, 2013 at 10:13

4 Answers 4

3

You can use uniq's destructive counterpart uniq! to determine if an array contains duplicates. It returns nil if no duplicates were found:

if ![var1, var2, var3].uniq!
  # no duplicates
end
1
  • Great, I knew that there is always a cool way to do such things in Ruby. thx!
    – 23tux
    Apr 12, 2013 at 12:46
3

One way might be using Array#uniq.

inputs = [var1, var2, var3]

if inputs.uniq == inputs
  # ...
end

# or

if inputs.uniq.length == inputs.length
  # ...
end
2

You could do something like this

a = [var1. var2, var3]

if a.length == a.uniq.length
 ..
end
1
  • thx for the reply! Your solution is like the one from Stefan (his is a little bit shorter), so I would love to give you also a questions solved
    – 23tux
    Apr 12, 2013 at 12:48
0

You can using a mapping to store them,and compare its length with your input variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.