June 16th, 2007

Comparison Problem in Ruby

Posted by Jeremy2 in General Musings / Rants

For the past few days I have immersed myself in Ruby on Rails, and for the most part I have been loving every minute of it. However, there was a problem I was having in my code that was driving me nuts. I think I spent nearly four hours on it until I figured out what the problem was, exactly. I had the following bit of code in my model:


def add_attribute_group (the_id)
current_attribute_groups.each do |v|
found = v.attribute_group_id == the_id
break if found
end
if !found && grp = AttributeGroup.find(the_id)
iag = ItemAttributeGroup.new({:attribute_group => grp, :item => self})
current_attribute_groups < < iag
end
end

Rails defines the foreign key ID (in this case attribute_group_id) as a string rather than a number, and so if you try to do a comparison to a number, this will not work! I’ve been spoiled by PHP which treats 3 and “3″ as the same thing. For instance:


$a = '3';
$b = 3;
$a == $b ; //This will return true

However it appears in Ruby:

a = 3
b = '3'
a == b #This will return false

I had to amend this line:

found = v.attribute_group_id == the_id

… to read like this:

found = v.attribute_group_id.to_i == the_id

Leave a reply

You must be logged in to post a comment.