方法的封裝
#方法的封裝一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)#結果相同新聞熱點
疑難解答