Memoize |
BasicWerk
EC Support
Technique
Facebook
|
20140817160907_ruby_def_method_args |
|
ruby_def_method_args
def が受け取る引数では相互参照、デフォルトの設定ができる。
def foo (n, m, s=n*m)
puts "#{n} x #{m} = #{s}"
end
# デフォルトを設定した引数は省略できる
foo(100, 200)
# => 100 x 200 = 20000
可変長の引数を受け取るときは変数の前にスターを付ける。 メソッド内で可変長変数を使うときはスターを取る。
def bar (f, *r)
print "First arg is #{f}, "
puts "Rest is #{r.inspect}"
end
bar("first", "second")
# => First arg is first, Rest is ["second"]
# 可変長引数は1つの時でもメソッドに渡された時点で配列に格納される。
bar("first", "second", "third")
# => First arg is first, Rest is ["second", "third"]
メソッドにブロックを渡した場合、メソッド内からは yield でブロックを参照する。
def hello (name)
yield("Hello, #{name}!")
end
# Hello, name! に対して色んな処理ができる
hello("John") {|str| puts str}
# => Hello, John!
hello("Paul") {|str| str}
# => "Hello, Paul!"
hello("Eric") {|str| str.scan(/\w+/)}
# => ["Hello", "Eric"]
initialize の最後の引数に & が付いている時、ブロックを渡すと Proc に変換され、new されたオブジェクトが保持する。 block_method.rb
#! /usr/bin/ruby
# coding: utf-8
class String_editor
def initialize (&p)
@p = p
end
def get_result (str)
@p.call(str)
end
end
cut_words = String_editor.new {|str| str.scan(/\w+/)}
p cut_words.get_result("Today is the day.")
# => ["Today", "is", "the", "day"]
上記のオブジェクトは initialize の時点で文字列をどう料理するかレシピを受け取って proc オブジェクトに保持する。 get_result メソッドの引数で渡された文字列をレシピ通りに料理して返す。
レシピが同じで、文字列(具材)が異なる処理が複数あるときに便利。
|
| © Shin Nakamura/BasicWerk 2014 |