方法的封装
#方法的封装一class Myclass def public_method end PRivate def private_method end protected def protected_method endend#方法的封装一class Myclass def public_method end def private_method end def protected_method end public :public_method public :private_method public :protected_methodend多功能型(Duck type)
class Duck def quack puts "quack!!" endendclass Mallard def quack puts "quaasdfasck!!" endendbirds = [Duck.new,Mallard.new,Object.new ]birds.each do |duck| duck.quack if duck.respond_to? :quack //检查是否有quack方法endcode block(一种匿名方法,或叫做closure)
one line
5.times {puts "Ruby rokes"}1.upto(5) { |x| puts x}more lines
people = ["Divid", "john","Mary"]people.each do |person| puts personendmore code block
#迭代造出另一个阵列(map)a = ['a','b','c','d','e','f']a.map {|x| x + '!'}puts a.inspect #=> ["a!", "b!", "c!", "d!", "e!", "f!"]#找出符合条件的值b = [1,2,3,4]b.find_all{|x| x % 2 ==0}b.inspect #=> [2, 4]#迭代碰到符合条件的删除c =["a", "b", "c", "d", "e", "f"]c.delete_if{|x| x >= "c"}c.inspect #=> ["a", "b"]#客制化排序d = [2,5,4,6]d.sort!{|a,b| a <=> b}d.inspect #=> [2, 4, 5, 6]计算总和(5..10).reduce {|sum,n | sum+n} # =>45#找出最长字符串longest = ["abc",'abcde','abcd','abcdefe']longest.reduce do |memo,Word| (memo.length > word.length)? memo :wordend # =>'abcdefe' #执行一次呼叫pre file = File.new("testfile",'r') 处理内容 file.close ruby习惯写法 File.open("testfile",'r') do |file| 处理内容 end #自动关闭文档Yield
1.在方法中使用yield来执行code block #定义方法 def call_block puts "start" yield yield puts "end" end call_block{puts "Block is cool"} #输出如下: start Block is cool Block is cool end2.带参数的code block def call_block yield(1) yield(2) yield(3) end call_block{|i| puts "#{i} Block is cool"} #输出如下: 1 Block is cool 2 Block is cool 3 Block is coolProc Object
def call_block(&block) block.call(1) block.call(2) block.call(3)endcall_block{|i| puts "#{i} Block is cool"}||先宣告一个Proc对象proc1 = Proc.new{|i| puts "#{i}: Block is cool"}proc2 = lambda{|i| puts "#{i}: Block is cool"}#输出如下 1 Block is cool 2 Block is cool 3 Block is cool传递不定参数的方法
def my_sum(*val) #val是个阵列 val.inject(0){|sum,v| sum+v}endmy_sum(1,2,3,4,5)# 输出 15参数尾数Hash,可省略{}
def my_print(a,b,options) puts a puts b puts options[:x] puts options[:y] puts options[:z]endmy_print("A","B",{x:1,y:2,z:3})my_print("A","B",x:1,y:2,z:3)#结果相同新闻热点
疑难解答