Skip to content

Instantly share code, notes, and snippets.

@jcartledge
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcartledge/5316875e6f90551947f5 to your computer and use it in GitHub Desktop.
Save jcartledge/5316875e6f90551947f5 to your computer and use it in GitHub Desktop.

Some notes about ruby syntax

Optional parens

When calling a function or method, parens are optional, so:

puts msg

is equivalent to:

puts(msg)

This makes code look clean but can also lead to ambiguity - e.g.:

log decode msg, level

could mean:

log(decode(msg, level))

or:

log(decode(msg), level)

For this reason it's usually the right thing to use parens even though they are optional (and even when the examples in the docs don't use them).

Implicit hashes

Compounding the situation is that you can use an implict hash as the final argument. The standard syntax for a hash is:

hash = {:key => "value", :key2 => "value2"}

Say we had a hash like:

{:class => "warning"}

And a function:

def p_tag content, options
  # some code
end

We could pass that into a function call like this:

p_tag "content", :class => "warning"

which is equivalent to:

p_tag("content", {:class => "warning"})

so it's basically a cheap way to simulate named arguments.

Because the hash uses commas to separate its members and the arguments to the function are also comma-separated we can only use this form for the final positional argument to avoid ambiguity.

Passing blocks into functions

A block in Ruby is a unit of code, similar but different to a function. They can be passed around similarly (but different) to how we pass higher order functions in JavaScript.

These aren't passed as regular arguments, but after the arguments like so:

File.open('filename.txt', 'r') do |f1|  
  while line = f1.gets  
    puts line  
  end  
end  

Blocks can be wrapeed in do..end or {..} so the above is equivalent to:

File.open('filename.txt', 'r') {|f1|  
  while line = f1.gets  
    puts line  
  end  
}

The convention is to use the {..} form for single line blocks and do..end for multiline blocks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment