Ruby - gregorymorrison/euler1 GitHub Wiki

Ruby, introduced in 1995, is a simple, dynamic, strongly typed, multiparadigm language that often gets compared to Python. Both serve the same niche, so pick one or the other to learn. I expected that getting a version of Euler1 in Ruby up and running would be an easiest case, which it turned out to be.

#!/usr/bin/ruby
# Euler1 in Ruby
 
def euler1(x)
    (0...x).select{|i| i if i%3==0 or i%5==0}.inject{|retval,j| retval+j}
end
 
puts "Euler1 = #{euler1(1000)}"

Notice that in Ruby, operations tend to be chained together. Another interesting aspect of Ruby is its blocks, e.g.: inject{|retval,j| retval+j}

Here it is again, for versions of Ruby 1.8.7+ that support the new .inject(:+) syntax. Note the concision here - an IO statement, a loop, a condition, and an accumulator, all in one line - very nice!

#!/usr/bin/ruby
# Euler1 in Ruby
 
def euler1(x) 
    (0...x).select{|i| i if i%3==0 or i%5==0}.inject(:+)
end

puts "Euler1 = #{euler1(1000)}"

Ruby may already be installed on your Linux box. If not, on Fedora simply yum install ruby. Then to execute your Ruby script, simply call it:

$ ./euler1.rb
233168
$