help with a simple method
Hi I'm trying to solve the exercise from https://github.com/alexch/learn_ruby
I must write a method which should开发者_高级运维 "multiplies two numbers" and "multiplies an array of numbers". I'm fresh to ruby and solved it, with only one method like 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 are better ways, so how can I improve this method? to a more ruby like syntax :)
The if l.is_a? Array
is not necessary because the way multi
is define, l
will always be an array.
The pattern
result = starting_value
xs.each {|x| result = result op x}
result
can be written more succinctly using xs.inject(starting_value, :op)
.
So you can write your code as:
def multi(*l)
l.flatten.inject(1, :*)
end
If you're ok, with calling the method as multi(*array)
instead of multi(array)
to multiply an array, you can leave out the flatten, as well.
精彩评论