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 Ruby Objects and Classes Build a Bank Account Class Implement the balance Method

Jasmin Myers
Jasmin Myers
2,461 Points

Key and Value?

def balance
    balance = 0.0
    @transactions.each do |transaction|
      balance += transaction[:amount]
    end
    return balance
  end

I would like to know if :amount is the key or value? Also, I would like to know why we put the colon in front of amount in order to call it.

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

:amount is the name of the key. The value will be whatever transaction[:amount] returns (think of value as the thing that can be accessed under the :amount key, or using that key). This specific key is of type Symbol, that is why it's written with a colon. Normally, nowadays, we write hashes in Ruby using the short notation, like this:

{ amount: 25 }

But in the old versions, this would be written as:

{ :amount => 25 }

The old way is still applicable today, and is used with other types of keys, but the new way is more concise and readable when key is of Symbol type.

Now, back to the Symbol thing and why it's used here: you can as well use other types for keys when creating hashes, for example a String:

transaction = { "amount" => 24 }

And then you would access the 24 value using the transaction["amount"] key. :amount and '"amount"` are two different things, although you could think of symbols as special kinds of strings. This answer may help you in understanding the topic further: https://stackoverflow.com/questions/16621073/when-to-use-symbols-instead-of-strings-in-ruby (it may, as well, confuse you, but be brave :) ).

Jasmin Myers
Jasmin Myers
2,461 Points

Thank you that helped a lot, I appreciate it!