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 Collections Build a Grocery List Program Build a Grocery List Program: Part 3

JJME Dynamos
JJME Dynamos
10,609 Points

Build a Grocery List Ruby - Why do we need .to_s to display array

def print_list(list) puts "List: #{list['name']}" puts "--------" list["items"].each do |item| puts"Item: " + item["name"] puts "quantity: " + item["quantity"].to_s ***** puts"---" end end

I have a general question in order to display the quantity in this method we have to convert the output to a string but why is that? I'm confused as to why doesn't ruby allow a fixednum class to return and only strings? i'm just trying to wrap my head around what rule applied toward array enforces this.

1 Answer

The '+' operator takes in two string arguments and returns a new string that's a concatenation of the two. The quantity variable contains an integer, and not a string. Therefore, you must first convert it to a string using to_s.

In other words, there's no '+' operator that takes in a string and an integer.

JJME Dynamos
JJME Dynamos
10,609 Points

Kin pi you're amazing. Thank you so much!