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!