Define_method에 인수를 어떻게 전달합니까?
-
01-07-2019 - |
문제
Define_method를 사용하여 정의되는 메소드에 인수를 전달하고 싶습니다. 어떻게 해야 합니까?
해결책
Define_method에 전달하는 블록에는 일부 매개변수가 포함될 수 있습니다.이것이 정의된 메서드가 인수를 받아들이는 방식입니다.메소드를 정의할 때 실제로는 블록에 별명을 붙이고 클래스에 대한 참조를 유지하는 것뿐입니다.매개변수는 블록과 함께 제공됩니다.그래서:
define_method(:say_hi) { |other| puts "Hi, " + other }
다른 팁
...선택적 매개변수를 원하는 경우
class Bar
define_method(:foo) do |arg=nil|
arg
end
end
a = Bar.new
a.foo
#=> nil
a.foo 1
# => 1
...원하는만큼 인수를
class Bar
define_method(:foo) do |*arg|
arg
end
end
a = Bar.new
a.foo
#=> []
a.foo 1
# => [1]
a.foo 1, 2 , 'AAA'
# => [1, 2, 'AAA']
...조합
class Bar
define_method(:foo) do |bubla,*arg|
p bubla
p arg
end
end
a = Bar.new
a.foo
#=> wrong number of arguments (0 for 1)
a.foo 1
# 1
# []
a.foo 1, 2 ,3 ,4
# 1
# [2,3,4]
...그들 모두
class Bar
define_method(:foo) do |variable1, variable2,*arg, &block|
p variable1
p variable2
p arg
p block.inspect
end
end
a = Bar.new
a.foo :one, 'two', :three, 4, 5 do
'six'
end
업데이트
Ruby 2.0에서는 이중 표시가 도입되었습니다. **
(별 2개) 어느 (나는 인용한다) 하다:
Ruby 2.0에는 키워드 인수가 도입되었으며 **는 *처럼 작동하지만 키워드 인수에 사용됩니다.키/값 쌍이 포함된 해시를 반환합니다.
...물론 정의 메소드에서도 사용할 수 있습니다 :)
class Bar
define_method(:foo) do |variable1, variable2,*arg,**options, &block|
p variable1
p variable2
p arg
p options
p block.inspect
end
end
a = Bar.new
a.foo :one, 'two', :three, 4, 5, ruby: 'is awesome', foo: :bar do
'six'
end
# :one
# "two"
# [:three, 4, 5]
# {:ruby=>"is awesome", :foo=>:bar}
명명된 속성의 예:
class Bar
define_method(:foo) do |variable1, color: 'blue', **other_options, &block|
p variable1
p color
p other_options
p block.inspect
end
end
a = Bar.new
a.foo :one, color: 'red', ruby: 'is awesome', foo: :bar do
'six'
end
# :one
# "red"
# {:ruby=>"is awesome", :foo=>:bar}
저는 키워드 인수, splat 및 double splat를 모두 하나로 사용하여 예제를 만들려고 했습니다.
define_method(:foo) do |variable1, variable2,*arg, i_will_not: 'work', **options, &block|
# ...
또는
define_method(:foo) do |variable1, variable2, i_will_not: 'work', *arg, **options, &block|
# ...
...하지만 이것은 작동하지 않습니다. 제한이 있는 것 같습니다.생각해 보면 splat 연산자는 "나머지 모든 인수 캡처"이고 이중 splat은 "나머지 모든 키워드 인수 캡처"이므로 이를 혼합하면 예상 논리가 깨질 수 있습니다.(이런 점을 증명할 만한 참고자료가 없군요!)
2018년 8월 업데이트:
요약 기사: https://blog.eq8.eu/til/metaprogramming-ruby-examples.html
Kevin Conner의 답변 외에도 :블록 인수는 메서드 인수와 동일한 의미를 지원하지 않습니다.기본 인수나 블록 인수를 정의할 수 없습니다.
이는 전체 메소드 인수 의미 체계를 지원하는 새로운 대체 "stabby 람다" 구문을 사용하는 Ruby 1.9에서만 수정되었습니다.
예:
# Works
def meth(default = :foo, *splat, &block) puts 'Bar'; end
# Doesn't work
define_method :meth { |default = :foo, *splat, &block| puts 'Bar' }
# This works in Ruby 1.9 (modulo typos, I don't actually have it installed)
define_method :meth, ->(default = :foo, *splat, &block) { puts 'Bar' }
2.2에서는 이제 키워드 인수를 사용할 수 있습니다.https://robots.thoughtbot.com/ruby-2-keyword-arguments
define_method(:method) do |refresh: false|
..........
end