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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Jasmin Myers](https://secure.gravatar.com/avatar/d8f1e7217c3a6e5c8f53c1cdd6dec276?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Jasmin Myers
2,461 PointsKey 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](https://uploads.teamtreehouse.com/production/profile-photos/103489/micro_IMG_3403.jpg)
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
2,461 PointsJasmin Myers
2,461 PointsThank you that helped a lot, I appreciate it!