How to iterate through an array starting from the last element? (Ruby) - ruby

I came with below solution but I believe that must be nicer one out there ...
array = [ 'first','middle','last']
index = array.length
array.length.times { index -= 1; puts array[index]}

Ruby is smart
a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }

array.reverse.each { |x| puts x }

In case you want to iterate through a range in reverse then use:
(0..5).reverse_each do |i|
# do something
end

You can even use a for loop
array = [ 'first','middle','last']
for each in array.reverse do
print array
end
will print
last
middle
first

If you want to achieve the same without using reverse [Sometimes this question comes in interviews]. We need to use basic logic.
array can be accessed through index
set the index to length of array and then decrements by 1 until index reaches 0
output to screen or a new array or use the loop to perform any logic.
def reverseArray(input)
output = []
index = input.length - 1 #since 0 based index and iterating from
last to first
loop do
output << input[index]
index -= 1
break if index < 0
end
output
end
array = ["first","middle","last"]
reverseArray array #outputs: ["last","middle","first"]

In a jade template you can use:
for item in array.reverse()
item

You can use "unshift" method to iterate and add items to new "reversed" array.
Unshift will add a new item to the beginning of an array.
While << - adding in the end of an array. Thats why unshift here is good.
array = [ 'first','middle','last']
output = []
# or:
for item in array # array.each do |item|
output.unshift(item) # output.unshift(item)
end # end
puts "Reversed array: #{output}"
will print: ["last", "middle", "first"]

We can also use "until":
index = array.length - 1
until index == -1
p arr[index]
index -= 1
end

Related

appending the outputs of an array method into another array

array3 =['Maths', 'Programming', 'Physics'], ['Maths', 'Intro to comp. science', 'Programming'], ['English', 'Intro to comp. science', 'Physics']
course = 'Programming'
index = []
array3.find_index do |i|
if array3.include?(course) == true
index << i
end
end
i created an array (array3) that contains the respective elements and i want to add the elements of array3 which hold the condition true but after executing the code i get a blank array like "[[], [], []]"
how can i fix this issue?
find_index does not iterate over indices. It iterates over values and returns the first index of the value that matches. It sounds like you want to iterate over every element, making note of all of the indices that match some condition.
To that end, you can use each_with_index.
index = []
array3.each_with_index do |courses, i|
if courses.include?(course) == true
index << i
end
end
or you can use each_index and filter the results.
index = array3.each_index.select { |index| array3[index].include? course }
or, filtering with each_with_index,
index = array3.each_with_index
.select { |list, _| list.include? course }
.map(&:last)
on Ruby 2.7 or newer, you can shorten this with filter_map.
index = array3.each_with_index
.filter_map { |obj, index| index if obj.include? course }
You can achieve this with each
array3 =['Maths', 'Programming', 'Physics'], ['Maths', 'Intro to comp. science', 'Programming'], ['English', 'Intro to comp. science', 'Physics']
course = 'Programming'
index = []
array3.each do |i|
if i.include?(course)
index << i
end
end

Ruby Count Array objects if object includes value

I have an array:
array = ['Footballs','Baseball','football','Soccer']
and I need to count the number of times Football or Baseball is seen, regardless of case and pluralization.
This is what I tried to do, but with no luck:
array.count { |x| x.downcase.include? 'football' || x.downcase.include? 'baseball' }
What is a right or better way to write this code? I am looking for 3 as an answer.
I would use count combined with a block that checks each element against a regular expression that matches the constraints you're looking for. In this case:
array.count { |element| element.match(/(football|baseball)s?\Z/i) }
This will match any of these elements: football, footballs, baseball, baseballs.
The s? makes the 's' optional, the i option (/i) makes the expression case insensitive, and the \Z option checks for the end of the string.
You can read more about Regexps in the Ruby docs: http://www.ruby-doc.org/core-2.0.0/Regexp.html
A great tool for playing with Regexps is Rubular: http://rubular.com/
If you give a block to the count method of array, it iterates over the array and counts the values for which you return true:
array.count do |x|
(x.downcase.include? 'footbal') || (x.downcase.include? 'baseball')
end
You can use inject to count each item and return the result.
array = ['Football','Baseball','football','Soccer']
count = array.inject({}) do |counter, item|
counter[item.downcase] ||= 0
counter[item.downcase] += 1
counter
end
# => {"football"=>2, "baseball"=>1, "soccer"=>1}
If you need to count a single value, it's even simpler.
array = ['Football','Baseball','football','Soccer']
count = array.inject(0) do |counter, item|
counter += (item.downcase == 'football' ? 1 : 0)
end
On one line
array = ['Football','Baseball','football','Soccer']
count = array.inject(0) { |counter, item| counter += (item.downcase == 'football' ? 1 : 0) }
To include pluralization, simply enhance the comparison.
Assuming you have Ruby on Rails installed for the singularize method (you don't actually need to run this in rails):
require 'active_support/inflector'
array = ['Footballs','Baseball','football','Soccer']
uniq = array.map { |s| s.downcase.singularize }.uniq
uniq.size # => 3
Using Rails and Ruby >= 2.7 you can do:
array = ['Footballs','Baseball','football','Soccer']
array.map(&:downcase).map(&:singularize).tally
=> {"football"=>2, "baseball"=>1, "soccer"=>1}

Ruby grocery list program

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.

How to determine if a record is the first/last one in an iteration?

Its a thing that made me thinking several times. In this example I have an array and this array has 10 values that should be seperated by commatas but after the last one there shouldnt be a commata so I used a counter:
data = ["john", "james", "henry", "david", "daniel", "jennifer", "ruth", "penny", "robin", "julia"]
counter = 0
count = data.size
sentence = String.new
data.each do |name|
if counter == (count-1)
sentence += name
else
sentence += "#{name}, "
end
counter += 1
end
But this is so dirty isnt there any method to find out if the current object (in this case "name") is the frist or the last one in the iteration?
in this specific case, data.join(', ') would do, more generally data.each {|d| #do stuff
unless d.equal? data.last}
You should just write data.join(', '). Anyway, answering your question:
Isn't there any method to find out if the current object is the first or the last one in the iteration?
xs = [1, 2, 3, 4]
xs.each.with_index do |x, index|
if index == 0
puts("First element: #{x}")
elsif index == xs.size - 1
puts("Last element: #{x}")
else
puts("Somewhere in the middle: #{x}")
end
end
You can use name==data.last if your array is of unique elements
Otherwise use directly
data.join(', ')

difficulty modifying two dimensional ruby array

Excuse the newbie question. I'm trying to create a two dimensional array in ruby, and initialise all its values to 1. My code is creating the two dimensional array just fine, but fails to modify any of its values.
Can anyone explain what I'm doing wrong?
def mda(width,height)
#make a two dimensional array
a = Array.new(width)
a.map! { Array.new(height) }
#init all its values to 1
a.each do |row|
row.each do |column|
column = 1
end
end
return a
end
It the line row.each do |column| the variable column is the copy of the value in row. You can't edit its value in such way. You must do:
def mda(width,height)
a = Array.new(width)
a.map! { Array.new(height) }
a.each do |row|
row.map!{1}
end
return a
end
Or better:
def mda(width,height)
a = Array.new(width)
a.map! { Array.new(height) }
a.map do |row|
row.map!{1}
end
end
Or better:
def mda(width,height)
a = Array.new(width){ Array.new(height) }
a.map do |row|
row.map!{1}
end
end
Or better:
def mda(width,height)
Array.new(width) { Array.new(height){1} }
end
each passes into the block parameter the value of each element, not the element itself, so column = 1 doesn't actually modify the array.
You can do this in one step, though - see the API docs for details on the various forms of Array#new. Try a = Array.new(width) {|i| Array.new(height) {|j| 1 } }
you can create it like this?
a=Array.new(width) { Array.new(height,1) }
column in your nested each loop is a copy of the value at that place in the array, not a pointer/reference to it, so when you change its value you're only changing the value of the copy (which ceases to exist outside the block).
If you just want a two-dimensional array populated with 1s something as simple as this will work:
def mda(width,height)
[ [1] * width ] * height
end
Pretty simple.
By the way, if you want to know how to modify the elements of a two-dimensional array as you're iterating over it, here's one way (starting from line 6 in your code):
#init all its values to 1
a.length.times do |i|
a[i].length.times do |j|
a[i][j] = 1
end
end

Resources