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 Part 3: Keeping Our Balance

vo thi quynh yen
vo thi quynh yen
3,129 Points

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

Why do I need to use the [] behind transaction? can't I use {}?

3 Answers

Michael Hulet
Michael Hulet
47,913 Points

You use square brackets ([]) to get values out of both arrays and hashes. This is called "subscripting". There's no difference in the way you access values between arrays and hashes. In fact, you can generally think of an array as a hash with only sequential FixNum keys

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

[] are usually used for array elements & the {} is used to group code so theyre 2 different things.

vo thi quynh yen
vo thi quynh yen
3,129 Points

but i thought because transactions is a hash, and a hash syntax is {}, so why do I have to use [] instead of {} when refering to an element in a hash?