Basic introduction to Ruby |
Ruby can be a very efficient and powerful language for various scripting tasks.
It is a more object oriented version of Python. While it lacks the richness of libraries which Python has, some might say that it is a more elegant language. Ruby also offers a fair bit of support for constructs often used in functional programming.
Simple Ruby tasks, so that you may get a glimpse of how elegant the syntax is.
A - B = elements in A but not in B
Symmetric difference = (B - A) union (A - B)
= x if y == 0
= y if x == 0
This may be used to verify whether a number is prime or not
Computing the cartesian product of sets
Cartesian product of [B, C, F] x [G, H, I] = [ [B,G], [B, H], [B, I], [C, G], [C, H], [C, I]]
irb(main):001:0> [1,2,3].product [4,5,6]
=> [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]
Computing the Difference and Symmetric Difference of Two Sets
B - A = elements in B but not in AA - B = elements in A but not in B
Symmetric difference = (B - A) union (A - B)
irb(main):002:0> a = [1, 4, 6]
=> [1, 4, 6]
irb(main):003:0> b = [2, 4, 6, 7]
=> [2, 4, 6, 7]
irb(main):004:0> a - b
=> [1]
irb(main):005:0> (a - b) + (b - a)
=> [1, 2, 7]
Computing the GCD using the Euclidean Method (recursive)
GCD (x, y) = GCD (x%y, y) if both (x > 0 and y > 0)= x if y == 0
= y if x == 0
def gcd(x,y)
if x % y == 0
y
else
gcd(y, x % y)
end
end
p gcd(4, 16)
#=> 4
Checking if a number is Prime
There is a "Prime" package in Ruby.This may be used to verify whether a number is prime or not
irb(main):008:0> require 'prime'
=> true
irb(main):009:0> Prime.prime?(10)
=> false
irb(main):010:0> Prime.prime?(13)
=> true