Ruby is more dynamic in nature. So Let’s see …
a1 = [ :first , :second , :third , :fourth ] #=> [:first, :second, :third, :fourth]
a1 = :first , :second , :third , :fourth #=> [:first, :second, :third, :fourth]
a1 = [ :first , :second , :third , :fourth ]
a2 = [ :before , a1 , :after ]
a2 #=> [:before, [:first, :second, :third, :fourth], :after]
a2 . flatten #=> [:before, :first, :second, :third, :fourth, :after]
Nice Ahh!!! …
a1 = [ :first , :second , :third , :fourth ]
a2 = [ :before , * a1 , :after ]
#=> [:before, :first, :second, :third, :fourth, :after]
x , y , z = 1 , 2 , 3
p x #=> 1
p y #=> 2
p z #=> 3
Wooo Wooo….
a1 = [ :first , :second , :third , :fourth ]
x , y , z = * a1
p x #=> :first
p y #=> :second
p z #=> :third
a1 = [ :first , :second , :third , :fourth ]
x , y , z = :before , * a1
p x #=> :before
p y #=> :first
p z #=> :second
But wait, there’s more….
a1 = [ :first , :second , :third , :fourth ]
* x , y , z = * a1
p * x #=> [:first, :second]
p y #=> :third
p z #=> :fourth
a1 = [ :first , :second , :third , :fourth ]
x , * y , z = * a1
p x #=> :first
p * y #=> [:second, :third]
p z #=> :fourth
This is the common practice that we used with methods parameter.
a1 = [ :first , :second , :third , :fourth ]
x , y , * z = * a1
p x #=> :first
p y #=> :second
p * z #=> [:third, :fourth]
a1 = [ :first , :second , :third , :fourth ]
first , * rest = * a1
p first #=> :first
p * rest #=> [:second, :third, :fourth]
Where am I going with this? Stay with me here.
def sum3 ( x , y , z )
x + y + z
end
triangle = [ 1 , 2 , 3 ]
p sum3 ( * triangle ) #=> 6
def greet ( greeting , * names )
names . each do | name |
p " #{ greeting } ! #{ name } "
end
end
greet ( 'Good Morning' , 'Vinay' , 'John' , 'Shane' )
#=> "Good Morning! Vinay"
#=> "Good Morning! John"
#=> "Good Morning! Shane"
def randon_draw ( num_times , num_draws )
num_times . times do
draws = num_draws . times . map { rand ( 10 )}
yield ( * draws )
end
end
randon_draw ( 5 , 3 ) do | first , * rest |
p " #{ first } #{ rest } "
end
#=> "1 [7, 3]"
#=> "4 [5, 2]"
#=> "5 [1, 7]"
#=> "2 [9, 2]"
#=> "8 [9, 1]"
Comments