IN RUBY LANGUAGE.
Write a single Ruby demo program that illustrates the use of all main Ruby iterators (loop, while, until, for, upto, downto, times, each, map, step, collect, select, reject). The program should have a few lines illustrating loop, followed by a few lines illustrating while, and so on).
PLEASE HAVE COPYABLE CODE. NOT A PICTURE. THANK YOU.
Loop
i = 0 loop do i += 1 puts i break # this will cause execution to exit the loop end
While:
x = 4
# using while loop
# here conditional is x i.e. 4
while x >= 1
# statements to be executed
puts "Hi"
x = x - 1
# while loop ends here
end
FOR:
i = "YO"
# using for loop with the range
for a in 1..5 do
puts i
end
Until:
var = 7
# using until loop
# here do is optional
until var == 11 do
# code to be executed
puts var * 10
var = var + 1
# here loop ends
end
EACH:
# using each iterator
# here collection is range
# variable name is i
(0..9).each do |i|
# statement to be executed
puts i
end
Collect:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# using collect iterator
# printing table of 5
b = a.collect{ |y| (5 * y) }
puts b
TIMES:
# using times iterator by providing
# 7 as the iterate value
7.times do |i|
puts i
end
UPTO:
# using upto iterator
# here top value is 4
# bottom value is 7
4.upto(7) do |n|
puts n
end
# here top > bottom
# so no ouput
7.upto(4) do |n|
puts n
end
DOWNTO:
# using downto iterator
# here top value is 7
# bottom value is 4
7.downto(4) do |n|
puts n
end
# here top < bottom
# so no output
4.downto(7) do |n|
puts n
end
STEP:
# using step iterator
# skipping value is 10
# (0..60 ) is the range
(0..60).step(10) do|i|
puts i
end
EACH_LINE:
# using each_line iterator
"Welcome\nto\nRailway\nPortal".each_line do|i|
puts i
end
MAP:
array = [1,2,3]
array.map { |n| n * 2 }
# [2, 4, 6] is output
STEP:
# Increment from 0 to 10, by 2 each time.
# ... Name the iteration variable "v".
0.step(10, 2) do |v|
puts v
end
Collect:
# Ruby code for collect() method
# declaring array
a = [1, 2, 3, 4]
# invoking block for each element
puts "collect a : #{a.collect {|x| x + 1 }}\n\n"
Select:
# declaring array
c = [18, 22, 3, 3, 50, 6]
# select
puts "select method : #{a.select {|num| num > 10 }}\n\n"
Reject:
# declaring array
c = [18, 22, 3, 3, 50, 6]
# reject
puts "reject method : #{a.reject {|num| num > 10 }}\n\n"
Get Answers For Free
Most questions answered within 1 hours.