RWVHP

geeky initals

Ruby If Shotcuts

February 28th, 2007

The if statement, sometimes you don’t want to type

if user.password == user.username
    # do something
  end

Sometimes you might just want to simply check that the value set isn’t nil

user.password ||= 'default_password'

Thats the same as writing

if user.password == nil
  user.password = 'default_password'
end

A slight variation of that would be

user.password = params[:password] || 'default_password'

Which would be the same as

if params[:password] != nil
  user.password = params[:password]
else
  user.password = 'default_password'
end

Theres probably more ways of doing things like this that I haven’t came across yet, if you know of others leave a comment.

About RWVHP

Photo of Vincent Palmer the site owner.

Vincent is a self-confessed geek, who's day job is as a Rails developer, outside of work he likes to play with home automation gadgets. He resides in Newcastle upon Tyne.

Page Sections

Copyright © 2008 Vincent Palmer