ruby文法3


rubyのコードブロック
コードブロックは名前のない方法と見なすことができ、彼自身もオブジェクトであり、Procクラスのインスタンスである.
匿名のコードブロックと2つの作成方法
かっこで囲む方法で、
のように
{puts "hello"}

もう1つはdoとendキーワードです
do
  puts "hello"
end

コードブロックを作成すると、メソッド呼び出しに関連付けることができます.メソッドではyieldを使用してコードブロックをコールバックできます.
次のようになります.
def test_function
 puts "     "
yield
 puts "     "
end
test_function{puts "hello"}
test_function do
 puts"this is do and end !"
end

出力:
     
hello
     
     
this is do and end !
     

 
コードブロック受信パラメータの定義は次のとおりです.
{|x| puts x}
do |x,y|
puts x+y
end

コールバック時は
yield 1
yield (1,2)

完全な例は次のとおりです.
def test_function(arg)
 yield arg
end
test_function("hello"){|x| puts x}
#   hello

反復はrubyライブラリでコードブロックを使用することが多い
次に、Arrayのeach機能を実現します.
class Array
def my_each
#    
  for i in(0..self.length-1)
  #                  
    yield self[i]
 end
 end
end
[1,2,3,4].my_each{|x| puts x}

コードブロックの作成はProcとlambdaでも作成できます
Lambdaで作成したコードブロックは、コードブロックにreturnが含まれているために返されません.これはProcとの違いです.
def proc_test
 f = proc { return " Proc       "  }
f.call
  return "proc_test    "
end
def lambda_test
  f = lambda {return " lambda       "  } 
  f.call
  return "lambda_test    "
end
puts proc_test
puts lambda_test

しゅつりょく
 Proc       
lambda_test    
 
例外処理
構成は次のとおりです.
begin
#       
rescue Exception1
 #  Exception1     
rescue Exception2
 #  Exception2     
rescue =>err
 #         
ensure
 #          ,   java  finally  
end

例:
x=10
y=0
begin
 puts x/y
rescue ZeroDivisionError
y=2
retry #retry          
ensure
  puts "     "
end