Byte Friendly

Random thoughts on programming and related topics.

Advanced Default Parameters

| Comments

Today I was quite amazed by one of Ruby features. It is about default values of method parameters. For example you can do something like this:

1
2
3
def get_current_actions(project_id, status_id = params[:status_id] || DEFAULT_STATUS_ID)
    # implementation goes here
end

The code is saying basically this: “if status_id is not passed explicitly, try to take its value from params array. If it doesn’t contain specified key, then fall back to a constant”. This feature (as almost all the rest of Ruby magic) made avaiable by Ruby’s nature: it is interpreted language. This type of code is totally unusual to guys like me, who come from the world of static typing and compiled languages. But I think I’m gonna get used to it :-)

Comments