第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

首頁 慕課教程 Ruby 入門教程 Ruby 入門教程 30 ruby 動態(tài)定義方法

動態(tài)定義方法

本章節(jié)我會為大家講一下 Ruby 元編程中如何動態(tài)定義方法。

1. 如何動態(tài)定義一個方法

我們會使用define_method來動態(tài)定義方法。

實例:

class Account
  attr_accessor :state

 (1..99).each do |i|
 	define_method("credit_#{i}".to_sym) do
 		self.state = state + i
 	end

 	define_method("debit_#{i}".to_sym) do
 		self.state = state - i
 	end
 end

  def initialize(state)
    @state = state
  end
end

account = Account.new(20)
account.credit_31
account.state # => 51
account.debit_45
account.state # => 6

方法會被顯示到 public_methods 列表中。

account.public_methods(false)
# [ ... , :credit_83, :debit_83, :credit_84, :debit_84, ...]
account.respond_to?(:debit_19)
# => true
method = account.public_method(:debit_19)
# => #<Method: Account#debit_19> 

2. 動態(tài)定義方法時傳遞參數

2.1 強制參數

實例:

class Bar
  define_method(:foo) do |arg1, arg2|
    arg1 + arg2
  end
end

a = Bar.new
a.foo
#=> ArgumentError (wrong number of arguments (given 0, expected 2))
a.foo 1, 2
# => 3

2.2 可選參數

class Bar
  define_method(:foo) do |arg=nil|
    arg
  end
end

a = Bar.new
a.foo
#=> nil
a.foo 1
# => 1

2.3 任意數量參數

實例:

class Bar
  define_method(:foo) do |arg=nil|
    arg
  end
end

a = Bar.new
a.foo
#=> nil
a.foo 1
# => 1

2.4 固定鍵值對的哈希參數

實例:

class Bar
  define_method(:foo) do |option1: 'default value', option2: nil|
    "#{option1} #{option2}"
  end
end

bar = Bar.new
bar.foo option2: 'hi'
# => "default value hi"
bar.foo option2: 'hi',option1: 'ahoj'
# => "ahoj hi"

2.5 任意鍵值對數量的哈希參數

實例:

class Bar
  define_method(:foo) do |**keyword_args|
    keyword_args
  end
end

bar = Bar.new
bar.foo option1: 'hi', option2: 'ahoj', option3: 'ola'
# => {:option1=>"hi", :option2=>"ahoj", :option3=>"ola"}

2.6 傳遞block

實例:

class Bar
  define_method(:foo) do |&block|
    p block.call
  end
end

bar = Bar.new
bar.foo do
  'six'
end

# => "six"

2.7 所有參數

實例:

class Bar
  define_method(:foo) do |variable1, variable2, *arg, **keyword_args, &block|
    p variable1
    p variable2
    p arg
    p keyword_args
    p block.call
  end
end

bar = Bar.new
bar.foo :one, 'two', :three, 4, 5, foo: 'bar', car: 'dar' do
  'six'
end

## will print:
:one
"two"
[:three, 4, 5]
{ foo: "bar", car: "dar" }
'six'

注意事項:傳遞所有參數需要按照普通參數、不指定數目的參數、哈希參數、block的順序來設置。

3. 小結

本章節(jié)中我們學習了使用define_method來動態(tài)定義方法,如何傳遞參數,以及傳遞參數的順序應該按照arg、*args、**keyword_args、block的順序來設置。