Today I Learned

hashrocket A Hashrocket project

Ruby optional arguments can come before required

I'm used to seeing optional arguments after required ones, as so:

require 'date'

def age(date, today=Date.today)
  (today - date) / 365.25 # good enough
end

birthdate = Date.parse("2011-06-15")

# How old am I today?
age(birthdate) #=> 4.583

# How old was I on the first?
age(birthdate, Date.parse("2016-01-01")) #=> 4.547

The second argument is optional.

However, you can also make the first argument optional:

def age(today=Date.today, date)
  (today - date) / 365.25 # good enough
end

birthdate = Date.parse("2011-06-15")

# How old am I today?
age(birthdate) #=> 4.583

# How old was I on the first?
age(Date.parse("2016-01-01"), birthdate) #=> 4.547

I don't recommend doing this. It's confusing.

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.