more ruby way of doing project euler #2

Posted by aharon on Stack Overflow See other posts from Stack Overflow or by aharon
Published on 2010-06-12T16:49:13Z Indexed on 2010/06/12 16:52 UTC
Read the original article Hit count: 298

Filed under:
|

I'm trying to learn Ruby, and am going through some of the Project Euler problems. I solved two as such:

def fib(n)
  return n if n < 2
  vals = [0, 1]
  n.times do
    vals.push(vals[-1]+vals[-2])
  end
  return vals.last
end
i = 1
s = 0
while((v = fib(i)) < 4_000_000)
  s+=v if v%2==0
  i+=1
end
puts s

While that works, it seems not very ruby-ish—I couldn't come up with any good purely Ruby answer like I could with the first one ( puts ( (0..999).inject{ |sum, n| n%3==0||n%5==0 ? sum : sum+n } )).

© Stack Overflow or respective owner

Related posts about ruby

Related posts about project-euler