I have a finished program, but now I need to convert an #Each loop to a #While loop. The loop should output almost the same information, but it throws me a 'directory.rb:24:in `print': no implicit conversion of Symbol into Integer (TypeError)' instead.
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
name = gets.chomp
while !name.empty? do
students << {name: name, cohort: :november}
puts "Now we have #{students.count} students"
name = gets.chomp
end
students
end
students = input_students
def print_header
puts "The students of Villains Academy"
puts "----------"
end
def print(students)
students.each.with_index(1) do |students, index|
puts "#{index} #{students[:name]}, #{students[:cohort]} cohort"
end
end
def print_footer(names)
puts "Overall we have #{names.count} great students"
end
print_header
print(students)
print_footer(students)
Works as expected. I'm trying:
def print(students)
i = 0
while i < students.length
puts "#{students[:name]}, #{students[:cohort]} cohort"
end
end
Why doesn't the #While loop work with similar input, and why is it trying to convert to an integer?
Because your #each loop was shadowing the students variable:
# v v
students.each.with_index(1) do |students, index|
puts "#{index} #{students[:name]}, #{students[:cohort]} cohort"
end
you iterate an array called students and then assign each element in the array to a variable named students. When you get rid of the each loop, you didn't change the block to stop looking at students, so it's now looking at the array. To get a single element try:
def print(students)
i = 0
while i < students.length
puts "#{students[i][:name]}, #{students[i][:cohort]} cohort"
end
end
while i < students.length
puts "#{students[:name]}, #{students[:cohort]} cohort"
end
students is an array. You can't address its elements with symbols. What you need to do is use i to fetch an element of students. You can call [:name] on that.
The mistake comes, I think, from poor naming in this snippet. And/or not understanding how each works.
students.each.with_index(1) do |students, index|
# ^^^^^^
# This here is called `students`, but its value is a single student,
# not a collection of students.
I need to update this hash with as many items as the user wants. And I have a problem with updating it.
It only shows the last input from user.
For example in i = 2, the hash will only show the second key and value added, and I want both. Or if i = 3 i need all three inputs.
puts "how may items to add in hash?"
i=gets.chomp.to_i
for i in 1..i
puts "add key"
key = gets.chomp
puts "add value"
value = gets.chomp.to_f.round(2)
project = Hash.new()
project = {key => value}
project.each do |key, value|
puts "#{key} \t - \t #{value}%"
end
end
Anyone that can help?
Just move your variable initialization our of the loop. Right now you rewrite your project with blank hash on each iteration. That's why it stores only the last item. Here is your possible code:
puts "how may items to add in hash?"
project = {}
i=gets.chomp.to_i
for i in 1..i
puts "add key"
key = gets.chomp
puts "add value"
value = gets.chomp.to_f.round(2)
project[key] = value
end
project.each do |key, value|
puts "#{key} \t - \t #{value}%"
end
project.values.inject(&:+)
PS: Prefer {} over Hash.new() (https://github.com/bbatsov/ruby-style-guide#literal-array-hash)
Try running this code.
When method1 is run, the hash is returned twice, meaning the hash is returned and printed as intended by the 'puts method1().inspect' command.
When method2 is run, and the loop is exited second time-around, by typing "no" or "n", a bunch of seemingly random numbers are printed, instead of a lovely hash. Why is this????
def method1
loop do
print "Item name: "
item_name = gets.chomp
print "How much? "
quantity = gets.chomp.to_i
hash = {"Item"=> item_name, "quantity"=> quantity}
puts hash.inspect
return hash
end
end
puts method1().inspect
def method2
loop do
print "Item name: "
item_name = gets.chomp
print "How much? "
quantity = gets.chomp.to_i
hash = {"Item"=> item_name, "quantity"=> quantity}
puts hash.inspect
print "Add another item? "
answer = gets.chomp.downcase
break if (answer == "no") || (answer == "n")
end
return hash
end
puts method2().inspect
You've accidentally discovered the Object#hash method. You don't declare hash outside the loop, so it is not in scope to return at the end. Instead, it returns the hash() method value, which is a big negative number for that instance.
Fire up irb, and just type hash, you'll see the same thing:
(505)⚡️ irb
2.1.2 :001 > hash
=> -603961634927157790
So instead, try this:
def method2
hash = {}
loop do
# ...
Also be aware you aren't adding to the hash, you're re-creating it every time.
In method2, you're trying to return something (hash) that has gone out of scope.
In method1, you're still inside the loop where hash was defined when you return it. In method2, you're outside of the scope where hash was defined, so it has an undocumented outcome. Redefined method2 like so:
def method2
hash = nil
loop do
print "Item name: "
item_name = gets.chomp
print "How much? "
quantity = gets.chomp.to_i
hash = {"Item"=> item_name, "quantity"=> quantity}
puts hash.inspect
print "Add another item? "
answer = gets.chomp.downcase
break if (answer == "no") || (answer == "n")
end
return hash
end
Now, even though hash was initially set to nil, its scope includes the entire method, and the value will be retained.
I am currently learning Ruby and I'm trying to write a simple Ruby grocery_list method. Here are the instructions:
We want to write a program to help keep track of a grocery list. It takes a grocery item (like "eggs") as an argument, and returns the grocery list (that is, the item names with the quantities of each item). If you pass the same argument twice, it should increment the 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 to figure out here how to return "2 eggs" by passing eggs twice
To help you count the different items you can use as Hash. A Hash is similar to an Array, but with Strings instead of Integers als an Index:
a = Array.new
a[0] = "this"
a[1] = "that"
h = Hash.new
h["sonja"] = "asecret"
h["brad"] = "beer"
In this example the Hash might be used for storing passwords for users. But for your
example you need a hash for counting. Calling grocery_list("eggs", "beer", "milk", "eggs")
should lead to the following commands being executed:
h = Hash.new(0) # empty hash {} created, 0 will be default value
h["eggs"] += 1 # h is now {"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 all the keys and values of a Hash with the each-loop:
h.each{|key, value| .... }
and build up the string we need as a result, adding
the number of items if needed, and the name of the item.
Inside the loop we always add a comma and a blank at the end.
This is not needed for the last element, so after the
loop is done we are left with
"2 eggs, beer, milk, "
To get rid of the last comma and blank we can use chop!, which "chops off"
one character at the end of a string:
output.chop!.chop!
One more thing is needed to get the complete implementation of your grocery_list:
you specified that the function should be called like so:
puts grocery_list("eggs", "beer", "milk","eggs")
So the grocery_list function does not know how many arguments it's getting. We can handle
this by specifying one argument with a star in front, then this argument will
be an array containing all the arguments:
def grocery_list(*items)
# items is an array
end
So here it is: I did your homework for you and implemented grocery_list.
I hope you actually go to the trouble of understanding the implementation,
and don't just copy-and-paste it.
def grocery_list(*items)
hash = Hash.new(0)
items.each {|x| hash[x] += 1}
output = ""
hash.each do |item,number|
if number > 1 then
output += "#{number} "
end
output += "#{item}, "
end
output.chop!.chop!
return output
end
puts grocery_list("eggs", "beer", "milk","eggs")
# output: 2 eggs, beer, milk
def grocery_list(*item)
item.group_by{|i| i}
end
p grocery_list("eggs", "eggs","meat")
#=> {"eggs"=>["eggs", "eggs"], "meat"=>["meat"]}
def grocery_list(*item)
item.group_by{|i| i}.flat_map{|k,v| [k,v.length]}
end
p grocery_list("eggs", "eggs","meat")
#=>["eggs", 2, "meat", 1]
def grocery_list(*item)
Hash[*item.group_by{|i| i}.flat_map{|k,v| [k,v.length]}]
end
grocery_list("eggs", "eggs","meat")
#=> {"eggs"=>2, "meat"=>1}
grocery_list("eggs", "eggs","meat","apple","apple","apple")
#=> {"eggs"=>2, "meat"=>1, "apple"=>3}
or as #Lee said:
def grocery_list(*item)
item.each_with_object(Hash.new(0)) {|a, h| h[a] += 1 }
end
grocery_list("eggs", "eggs","meat","apple","apple","apple")
#=> {"eggs"=>2, "meat"=>1, "apple"=>3}
Use a Hash Instead of an Array
When you want an easy want to count things, you can use a hash key to hold the name of the thing you want to count, and the value of that key is the quantity. For example:
#!/usr/bin/env ruby
class GroceryList
attr_reader :list
def initialize
# Specify hash with default quantity of zero.
#list = Hash.new(0)
end
# Increment the quantity of each item in the #list, using the name of the item
# as a hash key.
def add_to_list(*items)
items.each { |item| #list[item] += 1 }
#list
end
end
if $0 == __FILE__
groceries = GroceryList.new
groceries.add_to_list('eggs', 'eggs')
puts 'Grocery list correctly contains 2 eggs.' if groceries.list['eggs'] == 2
end
Here's a more verbose, but perhaps more readable solutions to your challenge.
def grocery_list(*items) # Notice the asterisk in front of items. It means "put all the arguments into an array called items"
my_grocery_hash = {} # Creates an empty hash
items.each do |item| # Loops over the argument array and passes each argument into the loop as item.
if my_grocery_hash[item].nil? # Returns true of the item is not a present key in the hash...
my_grocery_hash[item] = 1 # Adds the key and sets the value to 1.
else
my_grocery_hash[item] = my_grocery_hash[item] + 1 # Increments the value by one.
end
end
my_grocery_hash # Returns a hash object with the grocery name as the key and the number of occurences as the value.
end
This will create an empty hash (called dictionaries or maps in other languages) where each grocery is added as a key with the value set to one. In case the same grocery appears multiple times as a parameter to your method, the value is incremented.
If you want to create a text string and return that instead of the hash object and you can do like this after the iteration:
grocery_list_string = "" # Creates an empty string
my_grocery_hash.each do |key, value| # Loops over the hash object and passes two local variables into the loop with the current entry. Key being the name of the grocery and value being the amount.
grocery_list_string << "#{value} units of #{key}\n" # Appends the grocery_list_string. Uses string interpolation, so #{value} becomes 3 and #{key} becomes eggs. The remaining \n is a newline character.
end
return grocery_list_string # Explicitly declares the return value. You can ommit return.
Updated answer to comment:
If you use the first method without adding the hash iteration you will get a hash object back which can be used to look up the amount like this.
my_hash_with_grocery_count = grocery_list("Lemonade", "Milk", "Eggs", "Lemonade", "Lemonade")
my_hash_with_grocery_count["Milk"]
--> 1
my_hash_with_grocery_count["Lemonade"]
--> 3
Enumerable#each_with_object can be useful for things like this:
def list_to_hash(*items)
items.each_with_object(Hash.new(0)) { |item, list| list[item] += 1 }
end
def hash_to_grocery_list_string(hash)
hash.each_with_object([]) do |(item, number), result|
result << (number > 1 ? "#{number} #{item}" : item)
end.join(', ')
end
def grocery_list(*items)
hash_to_grocery_list_string(list_to_hash(*items))
end
p grocery_list('eggs', 'eggs', 'bread', 'milk', 'eggs')
# => "3 eggs, bread, milk"
It iterates an array or hash to enable building another object in a convenient way. The list_to_hash method uses it to build a hash from the items array (the splat operator converts the method arguments to an array); the hash is created so that each value is initialized to 0. The hash_to_grocery_list_string method uses it to build an array of strings that is joined to a comma-separated string.
Brand new to Ruby. Am trying to sort a de-duplicated list of email FROM (senders) with the # of emails sent. This code is working but it's sorting alphabetically. I can't figure out how to sort it so that most # of emails is on top, etc.
results = []
mail_count = imap.search(["SINCE", #this_week.strftime("%d-%b-%Y")]).each do |message_id|
envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
#from_array = envelope.from[0].name.to_a
results << #from_array
end
# make the hash default to 0 so that += will work correctly
from_count = Hash.new(0)
# iterate over the array, counting duplicate entries
results.each do |v|
from_count[v] += 1
end
from_count.sort_by do |k, v| v
puts "#{v} -- #{k}"
end
from_count.sort_by{|k,v| v }
Should do the trick.
You can then iterate over the sorted hash and print the results.
So then your code would look like this:
from_count.sort_by{|k,v| v }.first(10).each{|k,v| puts "#{v} -- #{k}" }
The sort_by sorts it, then when the sorting is done we print the results.