ruby - help with a simple method -
hi i'm trying solve exercise https://github.com/alexch/learn_ruby
i must write method should "multiplies 2 numbers" , "multiplies array of numbers". i'm fresh ruby , solved it, 1 method this:
def multi(*l) sum = 1 l.flatten! if l.is_a? array l.each{|i| sum = sum*i} return sum end
i'm sure there better ways, how can improve method? more ruby syntax :)
the if l.is_a? array
not necessary because way multi
define, l
array.
the pattern
result = starting_value xs.each {|x| result = result op x} result
can written more succinctly using xs.inject(starting_value, :op)
.
so can write code as:
def multi(*l) l.flatten.inject(1, :*) end
if you're ok, calling method multi(*array)
instead of multi(array)
multiply array, can leave out flatten, well.
Comments
Post a Comment