Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Syntax for Ruby method arguments (solved)

I was under the impression that when passing arguments into a method, the brackets can be omitted. So BankAccount.new("Jason") and BankAccount.new "Jason" are interchangeable.

However, when trying out the program in this video, I seem to have found an exception to this rule.

This causes a syntax error:

@transactions.push { amount: amount, memo: options[:memo] }

But this works:

@transactions.push({ amount: amount, memo: options[:memo] })

Anyone care to explain?

1 Answer

Tommy Morgan
STAFF
Tommy Morgan
Treehouse Guest Teacher

Hi Charles Manfre -

The rule you cite is generally true; there are however two exceptions. The first exception (and the most common) is that the arguments you're providing are ambiguous in some fashion. For example, consider the following:

method1 arg1, method2 arg2, arg3

This could be interpreted in two different ways:

method1(arg1, method2(arg2, arg3))

or

method1(arg1, method2(arg2), arg3)

...so the compiler will complain.

The second exception (and the one you're experiencing) has to do with the fact that the {} syntax in Ruby can mean one of two things: it can represent a hash or it can represent a block, like so:

my_hash = { test: :foo, bar: :baz }

vs.

my_list.map { |list_item| list_item.do_stuff }

When the {} syntax is used in a function call outside of the parentheses, Ruby assumes that you're passing a block to the function and tries to interpret it as such, which leads to the syntax error.

Hope that helps!