标签:
block_name{
statement1
statement2
..........
}#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
def test
puts "在 test 方法内"
yield
puts "你又回到了 test 方法内"
yield
end
test {puts "你在块内"}运行了这段后的效果是在 test 方法内 你在块内 你又回到了 test 方法内 你在块内在yield的部分运行了你调用时传入的块语句。
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
def test
yield 5
puts "在 test 方法内"
yield 100
end
test {|i| puts "你在块 #{i} 内"}#!/usr/bin/ruby
def test(&block)
block.call
end
test { puts "Hello World!"}是不是令你想起了javascript里面的回调函数?#!/usr/bin/ruby
BEGIN {
# BEGIN 代码块
puts "BEGIN 代码块"
}
END {
# END 代码块
puts "END 代码块"
}
# MAIN 代码块
puts "MAIN 代码块"一个程序可以包含多个 BEGIN 和 END 块。BEGIN 块按照它们出现的顺序执行。END 块按照它们出现的相反顺序执行。当执行时,上面的程序产生产生以下结果:BEGIN 代码块 MAIN 代码块 END 代码块
module Identifier statement1 statement2 ........... end模块常量命名与类常量命名类似,以大写字母开头。方法定义看起来也相似:模块方法定义与类方法定义类似。
#!/usr/bin/ruby # 定义在 trig.rb 文件中的模块 module Trig PI = 3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end
$LOAD_PATH << ‘.‘ require ‘trig.rb‘ y = Trig.sin(Trig::PI/4)注意这句话 $LOAD_PATH << ‘.‘ 这句话是把require的路径定到当前的文件路径,我刚开始require总是失败就是因为没有这句话
require_relative ‘trig.rb‘ y = Trig.sin(Trig::PI/4)
module Week
FIRST_DAY = "Sunday"
def Week.weeks_in_month
puts "You have four weeks in a month"
end
def Week.weeks_in_year
puts "You have 52 weeks in a year"
end
end#!/usr/bin/ruby
$LOAD_PATH << ‘.‘
require "support"
class Decade
include Week
no_of_yrs=10
def no_of_months
puts Week::FIRST_DAY
number=10*12
puts number
end
end
d1=Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months你会发现,有没有那行 include Week 代码执行结果根本就没有区别!module A def a1 end def a2 end end module B def b1 end def b2 end end class Sample include A include B def s1 end end samp=Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1
标签:
原文地址:http://blog.csdn.net/nsrainbow/article/details/50438140