Domanda

When I write methods in Ruby I often think "I bet this could be done simpler". Here is one example method. It adds all numbers starting at 1 until the number n. Is there a way to leave off the variable solution?

def sum n
    solution = 0
    for i in 1..n do
        solution += i
    end
    solution
end
È stato utile?

Soluzione

Using Enumerable#inject (or Enumerable#reduce):

(1..10).inject :+
# => 55

Altri suggerimenti

falsetru's is the shorthand answer for sum. But just to expand on that for your own benefit, inject normally looks more like this:

def sum n
  (1..n).inject {|result, i| result + i}
end

In this example, the result of the block is fed back in as result with each successive iteration, so it builds a cumulative total.

inject is very versatile, but there are plenty of other iterators which save you from managing a count variable. Look up times, each and map for starters.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top