Type casting in Ruby Saturday evening, 3 December 2005

Okay, you can mock me, i don’t care. I have a cold and am clearly not with it. If you haven’t used Ruby on Rails yet, then this tip will hopefully save you four hours time. That number will vary depending on intelligence, condition of health whilst coding, and background music. What am I talking about? Type casting in Ruby.

If you write dynamic web sites you know the scenario, you pass a page a parameter which it uses to locate a record in a database table or something of that nature. What i was trying to do was locate a record in an array of 'line_item' objects. If you’ve been reading DHH’s Agile Web Development with Rails you’ll know exactly what i mean. It took me around five minutes to write some code so that users can alter the quantity of a given item within their shopping cart. It took me three hours and 55 minutes to find the item within their cart. The reason? The product id within the line item was a number and the parameter i was passing was the only thing a parameter can be, a string.

def update_quantity(product, quantity)
   item = @items.find {|i| i.product_id == product}

product and quantity are parameters passed by a controller which have been params hash (basically a smart query string). The code above will never work. What’s missing is the magic ingredient to cast product into a number, in this instance an integer, String#to_i . Let’s see how that works out.

def update_quantity(product, quantity)
   item = @items.find {|i| i.product_id == product.to_i}

So Ruby’s ‘==’ is like a strict equality, (‘===’ if you’re using PHP or similar). As well as checking the value it also checks the data type.

 

Comments

 

Get Around

Journal
  • contemplating.Thoughts from a Christian world-view.
  • enjoying.Reviews of stuff i've been enjoying.
  • life.For those that would like to know what i'm up to, this is the place to look.
  • working.Thoughts and ideas on web development and projects i'm working on.
Other Places