javakoenig
javakoenig

Reputation: 33

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 :)

Upvotes: 1

Views: 87

Answers (1)

sepp2k
sepp2k

Reputation: 370465

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.

Upvotes: 4

Related Questions