All notes
LanguageReferenc

Basics

Comment

tutorialsPoint: ruby comments.



#!/usr/bin/ruby -w
# This is a single line comment.

=begin
This is a multiline comment and con spwan as many lines as you
like.
=end

Iterators

yield occurs sometimes in a definition of an iterator.

The following example defines an iterator repeat:



def repeat(num)
  while num > 0
    yield
    num -= 1
  end
end

repeat(3) { puts "foo" }
# foo
# foo
# foo

##########
# With retry, one can define an iterator which works something like ruby's standard while.

def WHILE(cond)
  return if not cond
  yield
  retry
end

i=0; WHILE(i<3) { print i; i+=1 }
# 012

Controls

rubyist.

For



#  If you're used to C or Java, you might prefer this.
for element in collection
  ...
end

#  A Smalltalk programmer might prefer this.
collection.each {|element|
  ...
}

Loop control



for i in 0..4
  print i
  if i == 2 and c == 0
    c = 1
    print "\n"
    retry
  end
end; print "\n"
# 012
# 01234

# Replacing retry with redo:
# 012
# 234

Case

Switch.



i=8
case i
  when 1, 2..5
    puts "1..5"
  when 6..10
    puts "6..10"
  end
# 6..10
# Here it uses internaly (2..5) === i, which is false.

# Regexp
case 'abcdef'
  when 'aaa', 'bbb'
    puts "aaa or bbb"
  when /def/
    puts "includes /def/"
  end
includes /def/

If, while



i=0

puts "It's zero." if i==0
# It's zero.

puts "It's negative." if i<0
#   nil

puts i+=1 while i<3
# 1
# 2
# 3

An unless is a negated if, and an until is a negated while.

Data types

Strings



puts "a\nb\nc"
# a
# b
# c
puts 'a\nb\n'
# a\nb\nc

"\n"
#   "\n"
'\n'
#   "\\n"

"abcd #{5*3} efg"
#   "abcd 15 efg"
var = " abc "
"1234#{var}5678"
#   "1234 abc 5678"

"foo" + "bar"
#   "foobar"
"foo" * 2
#   "foofoo"

a = "\n" * 2
a[0]
# "\n"

a = "parsley"
a[-1]
# "y"
a[10]
# nil
a[0,2]
# "pa"
a[-2,2]
$ "ey"
a[2..5]
# "rsle"
a[-5..-2]
# "rsle"
a[-2..-5]
# nil

Iterators



"abc".each_byte{|c| printf "<%c>", c}; print "\n"
# <a><b><c>

"a\nb\nc\n".each_line{|l| print l}
# a
# b
# c

Regexp

Regexp is directly put into /regexp/.

"=~" is a matching operator with respect to regular expressions; it returns the position in a string where a match was found, or nil if the pattern did not match.



"abcdef" =~ /d/
#   3
"aaaaaa" =~ /d/
#   nil

def chab(s)   # "contains hex in angle brackets"
   (s =~ /<0(x|X)(\d|[a-f]|[A-F])+>/) != nil
end

chab "Not this one."
#  false
chab "Maybe this? {0x35}"    # wrong kind of brackets
#  false
chab "Or this? <0x38z7e>"    # bogus hex digit
#  false
chab "Okay, this: <0xfc0004>."
#  true

##########
# A ruby app used to print the regexp result.
# Requires an ANSI terminal!

st = "\033[7m"
en = "\033[m"

puts "Enter an empty string at any time to exit."

while true
  print "str> "; STDOUT.flush; str = gets.chop
  break if str.empty?
  print "pat> "; STDOUT.flush; pat = gets.chop
  break if pat.empty?
  re = Regexp.new(pat)
  puts str.gsub(re,"#{st}\\&#{en}")
end

Array



## Conversion from/to strings.

str.split(":")
#   ["1", "2", "3"]
str = ary.join(":")
#   "1:2:3"

Hashes



h = {1 => 2, "2" => "4"}
#   {1=>2, "2"=>"4"}
h[1]
#   2
h["2"]
#   "4"
h[5]
#   nil

h[5] = 10    # appending an entry
#   10
h
#   {5=>10, 1=>2, "2"=>"4"}
h.delete 1   # deleting an entry by key
#   2
h[1]
#   nil
h
#   {5=>10, "2"=>"4"}

Functions

Arguments

skorks.com: method arguments in Ruby.


# Argument "c" with default value:
def some_method(a, b, c=25)
end

# Optional argument "p":
# After "a" and "b", the rest input will be assigned to "p" as an array.
def some_method(a, b, *p)
end

# Extended cases:
def some_method(a, b, *p, q)
end
# Testing:
some_method(25,35,45,55) - a=25, b=35, p=[45], q=55
some_method(25,35,45) - a=25, b=35, p=[], q=45
some_method(25,35,45,55,65,75) - a=25, b=35, p=[45,55,65], q=75

def some_method(a, b, c=5, *p, q)
end
# Testing:
some_method(25,35,45) - a=25, b=35, c=5, p=[], q=45
some_method(25,35,45,55) - a=25, b=35, c=45, p=[], q=55
some_method(25,35,45,55,65) - a=25, b=35, c=45, p=[55], q=65
some_method(25,35,45,55,65,75) - a=25, b=35, c=45, p=[55,65], q=75

def some_method(a, b=5, *p) - correct
def some_method(a, *p, b=5) - incorrect!!!

Classes

tutorialsPoint.com: ruby classes.

Variables



class Customer
   @@no_of_customers=0
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
end

cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

Class methods



class A
    # This is like class static method in C++.
    def A.A1()
    end
end