Dan Rosenstark
Dan Rosenstark

Reputation: 69777

Type-indifferent comparison in Ruby

I'm sure this is a basic question in Ruby:

Is there a way to check if

a == b

even if a is an integer and b is a string? I realize that I can do

a.to_s == b.to_s 

but I'd like to know if there's some other, better way.

Upvotes: 0

Views: 346

Answers (3)

edebill
edebill

Reputation: 7715

I haven't run into one, and Rails gets tripped up by this regularly, so I suspect that there's no slick way to do it - you have to force the to_s.

Upvotes: 0

edebill
edebill

Reputation: 7715

What about something like:

class Object
    def compare_as_strings(other)
      return self.to_s == other.to_s
    end
end

I hate extending something that fundamental, but this DOES work...

>> a = 1
=> 1
>> b = "1"
=> "1"
>> a.compare_as_strings(b)
=> true

Upvotes: 4

Telemachus
Telemachus

Reputation: 19705

I'm not sure that I understand the question. If I do understand it, I think you're trying to slip one by the interpreter:

telemachus ~ $ irb
irb(main):001:0> a = 1
=> 1
irb(main):002:0> b = '1'
=> "1"
irb(main):003:0> a == b
=> false

You can compare 1 and '1' all you like, but they aren't equal according to the way Ruby handles strings and numbers. In a nutshell, Ruby ain't Perl. (Edit: I should clarify. Clearly the number 1 is not the same thing as the string '1'. So it's not really a question of how Ruby handles them. If you compare them directly, they're just not the same. I just meant that Ruby doesn't do automatic conversions the way that Perl would. Depending on what language you come from and your attitude towards typing, this will make you happy or suprised or annoyed or some combination of these.)

Upvotes: 5

Related Questions