Ruby

Implementation of programming language Ruby

Standard implementation of Ruby, written in C.

This implementation is the de facto language reference.

Examples:

Factorial:

Example for versions Ruby 1.8.5

This example uses recursive factorial definition.

#! /usr/bin/env ruby
def factorial(n)
    if n == 0
        1
    else
        n * factorial(n - 1)
    end
end

0.upto(16) do |n|
    print(n, "! = ", factorial(n), "\n")
end

Factorial:

Example for versions Ruby 1.8.5

This example uses an iterative factorial definition.

def fact(n)
  (1..n).inject(1) {|a,b| a*b}
end

(0..16).each {|x| puts "#{x}! = #{fact(x)}"}

Fibonacci numbers:

Example for versions Ruby 1.8.5

This example uses recursive definition of Fibonacci numbers.

#! /usr/bin/env ruby
def fibonacci(n)
    if n < 3
        1
    else
        fibonacci(n - 1) + fibonacci(n - 2)
    end
end

(1..16).each {|n| puts fibonacci(n)}
puts "..."

Hello, World!:

Example for versions Ruby 1.8.5
puts "Hello, World!"

Factorial:

Example for versions Ruby 1.9

This example uses an iterative factorial definition

def fact(n)
  (1..n).reduce(:*)
end

(0..16).each {|x| puts "#{x}! = #{fact(x)}"}

Quadratic equation:

Example for versions Ruby 1.9
puts 'A = '
A = gets.chomp.to_f
if (A == 0)
   puts 'Not a quadratic equation.'
   return
end
puts 'B = '
B = gets.chomp.to_f
puts 'C = '
C = gets.chomp.to_f
 
D = B*B - 4*A*C
 
if (D == 0)
   puts 'x = '+(-B/2/A).to_s
else
   if (D > 0)
      puts 'x1 = '+((-B-Math.sqrt(D))/2/A).to_s
      puts 'x2 = '+((-B+Math.sqrt(D))/2/A).to_s
   else
      puts 'x1 = ('+(-B/2/A).to_s+','+(Math.sqrt(-D)/2/A).to_s+')'
      puts 'x2 = ('+(-B/2/A).to_s+','+(-Math.sqrt(-D)/2/A).to_s+')'
   end
end

CamelCase:

Example for versions Ruby 1.9
  1. Read the string from standard input (gets.chomp)
  2. Split the string into parts, separated with matches of regular expression, which describes a sequence of one or more non-letter characters
  3. Apply to each part function capitalise
  4. Concatenate the resulting strings (join) and print the result (puts)
puts gets.chomp.split( /[^a-zA-Z]+/ ).map {|w| w.capitalize}.join

CamelCase:

Example for versions Ruby 1.9

This works in a same way as this example, but scan extracts the matches of regular expression instead of discarding them and extracting parts of string between them, as split does.

puts gets.chomp.scan( /[a-zA-Z]+/ ).map {|w| w.capitalize}.join