Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!