odd And even number with yield
def odd_number
yield
end
(1..9).each_with_index do |odd_no,index|
if (index %2 ==0) then
odd_number { puts odd_no }
end
end
=========================================================================
def odd_number
yield
end
arr = []
(1..9).each do |x|
if x%2 !=0
arr << odd_number {x}
end
end
p arr
==========================================================================
def unique_names(names1, names2)
arr = names1 + names2
aa = []
arr.uniq.each do |a|
aa << a
end
return aa
end
names1 = ["Ava", "Emma", "Olivia"]
names2 = ["Olivia", "Sophia", "Emma"]
puts(unique_names(names1, names2)) # should print Ava, Emma, Olivia, Sophia
==========================================================================
def group_by_owners(files)
return nil
end
files = {
'Input.txt' => 'Randy',
'Code.py' => 'Stan',
'Output.txt' => 'Randy'
}
h = Hash.new{|h,k| h[k] = []}
files.map {|k,v| h[v]<< k}
puts h
==========================================================================
aa = []
x = 1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
aa = ["x is 1"]
else
puts "I can't guess the number"
end
p aa
==========================================================================
$age = 120
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end
==========================================================================
$i = 0
$num = 5
while $i < $num do
puts("Inside the loop i = #$i" )
$i +=1
end
==========================================================================
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
a = [1,2,3,4,5]
b = a.collect{|x| 2*x}
a << b
p b
Comments
Post a Comment