Ruby Grammer

Author: satoshiokita

DATE:2005/11/05 TIME:23:23:39 JST

Contents

00_helloworld

fliename: 00_helloworld.rb


#!/usr/bin/ruby

print "hello world!\n"

p "hello world!\n"

Return Contents

10_keyword_list

fliename: 10_keyword_list.rb


#!/usr/bin/ruby

=begin
BEGIN
END
alias
and
begin
break
case
class
def
defined?
do
else
elsif
end
ensure
false
for
if
in
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
yield
=end

Return Contents

20_comment

fliename: 20_comment.rb


# one line comment

# one line comment sample hogehogeho

=begin
 multi line comments sample
 hoge comment.
=end

=begin
= from =begin to =end.
= you can write a equal characer.
=end



Return Contents

21_heredoc

fliename: 21_heredoc.rb


#!/usr/local/bin/ruby 
#
# $Id: 21_heredoc.rb 1190 2005-11-05 14:23:33Z s-okita $
# Author : satoshiokita
# $Date: 2005-11-05 23:23:33 +0900 (土, 05 11 2005) $
# $Rev: 1190 $
print 

Return Contents

25_array

fliename: 25_array.rb


#!/usr/local/bin/ruby
# 
# Ruby has not primitive array. a 'Array' define object.
#
aryObject = [ "ruby", "java", "python" ]
p aryObject.class 

print aryObject[1], "\n"

Return Contents

26_array_iterator

fliename: 26_array_iterator.rb


#!/usr/local/bin/ruby
# 
# Ruby has not primitive array. a 'Array' define object.
# Operate by Iterator
#
aryObject = [ "ruby", "java", "python" ]
p aryObject.class 

aryObject.each { |item|
  print item, "\n"
}

Return Contents

27_hash

fliename: 27_hash.rb


#!/usr/local/bin/ruby
#
# Hash 
# * like a Hash in Perl
# * like a java.util.Map in Java
#
lang = {
  "Java" =>gt; "James Gosling",
  "Ruby" =>gt; "Matz"
}

print lang["Java"], "\n"
print lang["AAAA"], "\n"


Return Contents

28_hash_iterator

fliename: 28_hash_iterator.rb


#!/usr/local/bin/ruby
#
# Hash 
# * like a Hash in Perl
# * like a java.util.Map in Java
#
lang = {
  "Java" =>gt; "James Gosling",
  "Ruby" =>gt; "Matz"
}

print lang["Java"], "\n"
print lang["AAAA"], "\n"

# Iterator sample
# get KEY set only.
lang.each_key { |i|
  print i, "\n"
}

# get Value set only.
lang.each_value { |i|
  print i, "\n"
}

# get Key and Value
lang.each { |key, value|
  print key,"=",value,"\n"
}

Return Contents

30_statement

fliename: 30_statement.rb


=begin
 * variable
 * constant
 * literal
 * expression
 * 
 * control statements.
 * called method
 * class definition
 * method definition
=end

Return Contents

31_substitue

fliename: 31_substitue.rb


#
# substitute primary level.
#
=begin

 the Ruby language has not '++' operator and so on.
 if you has learned C/C++ like programming, rewrite following.
 * C/C++ like 
 int i = 0;
 i++;
 * Ruby
 i = 0
 i += 1

 * Why has not a '++' operator ? 
   Maybe... When Programming Language has a '++' operator, 
   i++, ++i difference problem occured, so Ruby erese '++' operator.
   above problem sample in C/C++ like language.
  
   # i++  
   int i = 0;
   int calc_result = 0;
   calc_result = i++;   # calc_result equal 0.

   # ++i  
   int i = 0;
   int calc_result = 0;
   calc_result = ++i;   # calc_result equal 1.
  
   above sample so easy, but this operator be used arguments for 
   funcition(method) in C/C++, Java  

PRIORITY HIGH LEVEL
::
[]
+ ! ~
**
-
* / %
+ -
gt;>gt;
&
| ^
>gt; >gt;= gt; == === != =~ !~
&&
||
.. ...
?:(condition operation)
=(+=, -= ... )
not
and or
PRIORITY LOW LEVEL
=end

Return Contents

32_literal_number

fliename: 32_literal_number.rb


#
# literal number
#

decimal = 123
p decimal

signed_decimal = -123
p signed_decimal

float_number = 123.45
p float_number

float_number2 = 1.2e-3
p float_number2

# hexica decimal
hex = 0xffffffff   
hex = 0xffff_ffff # same.ignore underline.

p hex

# binary
bin = 0b0101
p bin

# oct decimal
oct = 0567
# oct = 0o567 is supported ruby 1.7 feature.
p oct

# charactor code
ascii = ?a

p ascii

Return Contents

33_literal_string

fliename: 33_literal_string.rb


#
result = 1 + 2 / 3 * 4
p result

#
# join strings using space.
#
print  "Hello" "World\n"

# expend expression
print "Result= #{result}" "\n"
print "Result= ${result}" "\n"   # cannot expand 
print "Result= #{$result}" "\n"  # cannot expand

# Ruby can change String literal quote.
# default like other language
print "hello\n"

#
# change quote
#
print %q!Hello print double quote""! "\n"
print %!this sample can change quote '"'" yahoo! "\n"
print %Q( OH! Ruby is cool \n)

Return Contents

36_regular_expression

fliename: 36_regular_expression.rb


#!/usr/local/bin/ruby
#
# Ruby has a '=~' Regular Expression like a Perl.
#
target="happy ruby"

if /^happy/=~ target
  print target,"\n"
end

Return Contents

37_condition_expression

fliename: 37_condition_expression.rb


#
# control structure
#

#
# general condition
# 
age = 27
if age >gt;= 20 then
  print "adult\n"
elsif age >gt;= 15 then
  print "young\n"
else
  print "child\n"
end

#
# Ruby is false or nil as false, other is true.
#
$DEBUG = 1;
print "DEBUG_MODE\n" if $DEBUG

$DEBUG = 0;
print "DEBUG_MODE\n" if $DEBUG

$DEBUG = nil;
print "DEBUG_MODE\n" if $DEBUG

$DEBUG = false;
print "DEBUG_MODE\n" if $DEBUG

#
# if gt; unless
#
# unless cannot use elsif
unless true
  print "false\n"
else
  print "true\n"
end
 

Return Contents

38_case_expression

fliename: 38_case_expression.rb


#
# case expression
# Ruby case statement is not fall down like a C/C++ case statement.
# so Ruby has not case-break logic. this syntax is cool!
# 
test_id = 5 
case test_id
 when 0, 1
   print "TEST_ID= #{test_id}\n"
 when 2, 3
   print "HOGE\n"
 else
   print "other language is defualt\n"
end

test_id = 6
if 0 === test_id or 1 === test_id
  print "TEST_ID= #{test_id}\n"
elsif 2 === test_id or 3 === test_id
  print "HOGE\n"
else
  print "other language is default\n"
end

Return Contents

39_1_loop_while

fliename: 39_1_loop_while.rb


#
# loop expression
#
i = 0
while i 

Return Contents

39_2_loop

fliename: 39_2_loop.until.rb


#
# until
#
i = false
cnt = 0 
until i
  print "until loop\n"
  cnt += 1
  if cnt == 3 then
    i = true
  end
end

Return Contents

39_3_loop_for

fliename: 39_3_loop_for.rb


#
# for (like a shell for statement. not c/c++, Java for looping)
#
for i in [1, 2, 3]
  print i, "\n"
end


for i in 1..10
  print i, "\n"
end

Return Contents

39_4_loop_control_next

fliename: 39_4_loop_control_next.rb


#
# next like a continue
#
cnt = 0
while cnt gt; contiure in C/C++ and Java.
  
  # other message are not print.
  print "HELLO"
  print "HOGEHOGE"
end

Return Contents

39_5_loop_control_redo

fliename: 39_5_loop_control_redo.rb


#
# redo
# redo statement contiure current loop process. 
# but it isnot check of loop condition
#
cnt = 0
while cnt 

Return Contents

39_6_loop_control_retry

fliename: 39_6_loop_control_retry.rb


#
# retry
#

hi_counter = 0
for i in 1..5
  p i
  hi_counter += 1
  if hi_counter == 10
    break
  end
  retry if i == 2
end

Return Contents

40_local_variable

fliename: 40_local_variable.rb



2.times {

  p defined?(v)

  # declare 'v' local variable and initialize to 1.
  v = 1; 

  p v
}

Return Contents

42_global_variable

fliename: 42_global_variable.rb


$global_hoge_variable

#
# value of UNinitialized global variable return 'nil' object.
#
p $global_hoge_variable


#
# substitute string for global variable.
#
$global_hoge_variable = "HELLO GLOBAL HOGE"


p $global_hoge_variable

Return Contents

46_constant

fliename: 46_constant.rb


HOGE_CONSTANT = "CONST HOGE!!"

p HOGE_CONSTANT

# re-substitute
# when execute program, print warning message.
#
HOGE_CONSTANT = "CONST FUGA!!"

p HOGE_CONSTANT

#
# when undefined constant variable execute, occure a NameError exception
#
p BUHOO_CONSTANT

Return Contents

47_boolean_variable

fliename: 47_boolean_variable.rb


# Ruby has nil, true, and false variable as OBJECT!.

#
# true variable mean true bool value, true in other language.
#

p true

#
# true is unique object in TrueClass
#

p true.type

#
# false variable mean false bool value, false in other language.
#

p false

#
# true is unique object in FalseClass
#

p false.type

Return Contents

48_nil_variable

fliename: 48_nil_variable.rb


# Ruby has nil, true, and false variable as OBJECT!.

#
# nil variable mean NULL, null in other language.
#

p nil

#
# nil is unique object in NilClass
#
p nil.type

Return Contents

49_other_variable

fliename: 49_other_variable.rb


# refer source file name variable like a C Language.

p __FILE__

# refer source code line like a C Language.

p __LINE__

Return Contents

50_class_variable

fliename: 50_class_variable.rb


# class definition by 'class' keyword
class Hoge

  #
  # class variable definition by @@.
  #
  @@hoge_class_variable = 1

end

#
# CAUTION!!: Ruby language CAN NOT call class variable out of class.
#
p Hoge.hoge_class_variable

Return Contents

51_class_method

fliename: 51_class_method.rb


# class definition by 'class' keyword
class Hoge

  #
  # class variable definition by @@.
  #
  @@hoge_class_variable = 1

  #
  # class method definition by 'def' keyword and 'self' keyword
  # when the 'self' statment use, you will save modifiy to name of method.
  #
  def self.printClassValue
    p @@hoge_class_variable
  end

end

#
# call class method.
#
Hoge.printClassValue

Return Contents

55_instance_variable

fliename: 55_instance_variable.rb


# class definition by 'class' keyword
class Hoge

  #
  # instance variable definition by @.
  #
  @hoge_instance_variable = 1

end

#
# CAN NOT call in default. because it has Private privilege.
#
# p Hoge.new.hoge_instance_variable
#

Return Contents

56_instance_method

fliename: 56_instance_method.rb


#
# instance method. in Class or in My created class.
#

class Hoge 

  # instance variable for Class. this mean in Class class 
  @instance_value = 10000
  
  def printHello

    # instance variable. this mean in Hoge class
    p @instance_value
  end

end

obj = Hoge.new
obj.printHello

p obj.printHello.type

Return Contents

57_instance_method

fliename: 57_instance_method.rb


#
# instance method. in Class or in My created class.
#

class Hoge 
  
  def setup
    # instance variable. this mean in Hoge class
    @instance_value = 100
  end

  def printInstanceVariable
    p @instance_value
  end

end

obj = Hoge.new
obj.setup
obj.printInstanceVariable

Return Contents

58_accessor

fliename: 58_accessor.rb


#
# accessor ( as know as getter setter method. )
# 

class TestAccessor
  attr_accessor :name
end

obj = TestAccessor.new

# call setter
obj.name = 100

# call getter
p obj.name

Return Contents

59_accessor_like_java

fliename: 59_accessor_like_java.rb


#
# accessor ( as know as getter setter method. ) 
# java like type.
# 

class TestAccessor
  #
  # ruby accessor like a Microsoft .NET coding.
  # attr_accessor :name

  def name
    @name
  end

  def name=(str)
    @name = str
  end
  
end

obj = TestAccessor.new

# call setter
obj.name = "Like a Java Language."

# call getter
p obj.name

Return Contents

60_module

fliename: 60_module.rb


#
# Module and Module method.
#
# Ruby FAQ 6.8 
# Q.What's difference class and module.
# A. Module can not instantiate. class cannot use include statement.
#
module Hoge

  # module method (not static method.)
  def pMessage
    p "HELLO Module"
  end
end

# check
p defined?(Hoge)
p Hoge.type

# occured 'NameError' 
# p Hoge.pMessage

#
# when use Module, developer define include statement.
#
include Hoge

Hoge.pMessage

Return Contents

61_1_1_module_include_any_file

fliename: 61_1_1_module_include_any_file.rb


require "61_1_2_module_include_TestData"
require "61_1_3_module_include_TestModule"
#
# ruby load at once so it has not occured error.
#
require "61_1_3_module_include_TestModule.rb"

include TestModule

obj = TestData.new

obj.getInstan

Return Contents

61_1_2_module_include_TestData

fliename: 61_1_2_module_include_TestData.rb


class TestData

  @@hogeStatica = "Statica"

  @hogeInstan

  def self.getStatica
    p @@hogeStatica
  end

  def getInstan
    @hogeInstan = "sssss"
    p @hogeInstan
  end

end

Return Contents

61_1_3_module_include_TestModule

fliename: 61_1_3_module_include_TestModule.rb


module TestModule
  def printHello
    print "Hello Module\n"
  end
end

Return Contents

61_module_static_method

fliename: 61_module_static_method.rb


#
# Module static method.
#
# Ruby FAQ 6.8 
# Q.What's difference class and module.
# A. Module can not instantiate. class cannot use include statement.
#
module Hoge
  def self.pMessage
    p "HELLO Module"
  end
end

# check
p defined?(Hoge)
p Hoge.type

# occured 'NameError' 
# p Hoge.pMessage

#
# when use Module, developer define include statement.
#
include Hoge

Hoge.pMessage

Return Contents

62_mixin

fliename: 62_mixin.rb


#
# Multiple inheritance in Ruby is said 'mixin'.
#

module Caffee

  def caffee
    @caffee
  end
  def caffee=(str)
    @caffee = str 
  end

  def printCaffee
    @caffee
  end

  def printHello
    print "Hello Caffee\n"
  end
end

module Milk

  def printMilk
   @milk = 369
     @milk
  end

  def printHello
    print "Hello Milk\n"
  end

end

#
# multiplicty extends
#
class MilkCaffee
  include Caffee
  include Milk

  # A ancestors method print class hieralcy 
  p ancestors
end

obj = MilkCaffee.new

obj.printHello

Return Contents

65_exception

fliename: 65_exception.rb


#
# exception
#
begin
  print "program start\n"
 
  # exception occured
  raise "hoge exception!" 
  print "fugafuga\n"
  
  
rescue RuntimeError =>gt; evar 
  p $!
  p evar
  print "\n exception end\n"

else 
  print "..."
end

Return Contents

66_BEGIN_END_aspect

fliename: 66_BEGIN_END_aspect.rb


#
# BEGIN block is pre-process
# END block is post-process
# 
# aspective moving!!
#

BEGIN {
  print "pre execute\n"
}

END {
  print "post execute\n"
}

def helloPrint
  print "hello\n"
end

helloPrint

Return Contents

70_alias_global_variable

fliename: 70_alias_global_variable.rb


#
# operation for always defined statement.
#
# alias
#


# declare global variable
$global_my_hoge = "HOGE GLOBAL!!"

p $global_my_hoge
p $global_my_hoge.type

#
# alias new name for old name
#
alias $global_hoge $global_my_hoge

p $global_hoge
p $gloval_hoge.type

Return Contents

71_alias_method

fliename: 71_alias_method.rb


#
# operation for always defined statement.
#
# alias
#

class Hello

  def printHello
    p "Hello"
  end

  #
  # alias new name for old name
  #
  alias :printOhayou :printHello 
end

Hello.new.printHello
Hello.new.printOhayou

Return Contents

80_execute_command

fliename: 80_execute_command.rb


#
# execute command
#
str = `uname -a`
p str

Return Contents

81_reflection

fliename: 81_reflection.rb


#
# Ruby Reflection
#
require "61_1_2_module_include_TestData"

# a 'instance_methods' reflection method.
o = TestData.instance_methods

#
# Ruby 1.6 has a 'type' method. but 1.8 replace a 'class' method.
# when you used it in 1.8, print warning message.
#
#
p o.class
# p o.type

o.each { |i|
  print i , "\n"
}

testString = "hello"

# print all method.
testString.methods


Return Contents

82_load_vs_require

fliename: 82_load_vs_require.rb


#
# What's load and require statement. and different load from require.
#
=begin
 Ruby has two load mecanizm methods.
   * load
   * require
 When you want library loading, use 'require' and other file loding use 'load'


 * four point require
   * retreave file from load path
   * can load extendable library
   * cut extention (ex, .rb or .so)
   * safe load, save to load same file.

  confirm ruby load path follow one line script.
  $ruby -e 'puts $:'
  Ruby has load path in a '$:' of gloval variable.
=end

# confirm ruby load path in this file.
buff=`ruby -e 'puts $:'`
print buff

# loading buildin API by using require statement.
require "net/ftp"

# a '$"' of glovalvariale mean stataus for saving duplicate loading.
p $"

# confirm to save duplicate loding.
require "net/ftp"
p $"

# generally, this loading lock mechanizm cannot modify application developer 
# but Rubyist (Ruby hacker) can modify... maybe reason Ruby is script language.
#
#$"= []
#p $"

#
# load
#
# load statement is easy. a load only ruby program aka (.rb) loading.
# and cannot ommit extension (.rb)
# 
#
load 'XXXX.rb'

Return Contents

99_REFFERENCE

fliename: 99_REFFERENCE.rb


[The Object-Oriented Scripting Language Ruby ]
* http://www.ruby-lang.org/ja/

[LOVE RRUBY NET. - Chapter18. Load ]
* http://i.loveruby.net/ja/rhg/load.html

Return Contents