Ruby grocery list program -


i learning ruby , i'm trying write simple ruby grocery_list method. here instructions:

we want write program keep track of grocery list. takes grocery item (like "eggs") argument, , returns grocery list (that is, item names quantities of each item). if pass same argument twice, should increment quantity.

def grocery_list(item)   array = []   quantity = 1   array.each {|x| quantity += x }   array << "#{quantity}" + " #{item}" end  puts grocery_list("eggs", "eggs")  

so i'm trying figure out here how return "2 eggs" passing eggs twice

to count different items can use hash. hash similar array, strings instead of integers als index:

a = array.new a[0] = "this" a[1] = "that"  h = hash.new h["sonja"] = "asecret" h["brad"] = "beer" 

in example hash might used storing passwords users. example need hash counting. calling grocery_list("eggs", "beer", "milk", "eggs") should lead following commands being executed:

h = hash.new(0)   # empty hash {} created, 0 default value h["eggs"] += 1    # h {"eggs"=>1} h["beer"] += 1    # {"eggs"=>1, "beer"=>1} h["milk"] += 1    # {"eggs"=>1, "beer"=>1, "milk"=>1} h["eggs"] += 1    # {"eggs"=>2, "beer"=>1, "milk"=>1} 

you can work through keys , values of hash each-loop:

h.each{|key, value|  .... } 

and build string need result, adding number of items if needed, , name of item. inside loop add comma , blank @ end. not needed last element, after loop done left with

"2 eggs,  beer,  milk, " 

to rid of last comma , blank can use chop!, "chops off" 1 character @ end of string:

output.chop!.chop! 

one more thing needed complete implementation of grocery_list: specified function should called so:

puts grocery_list("eggs",  "beer", "milk","eggs") 

so grocery_list function not know how many arguments it's getting. can handle specifying 1 argument star in front, argument array containing arguments:

def grocery_list(*items)    # items array end     

so here is: did homework , implemented grocery_list. hope go trouble of understanding implementation, , don't copy-and-paste it.

def grocery_list(*items)   hash = hash.new(0)   items.each {|x| hash[x] += 1}    output = ""   hash.each |item,number|       if number > 1         output += "#{number} "       end      output += "#{item}, "   end    output.chop!.chop!   return output end  puts grocery_list("eggs",  "beer", "milk","eggs") # output: 2 eggs,  beer,  milk  

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -