programing

_method를 정의하기 위해 인수를 전달하는 방법은 무엇입니까?

jooyons 2023. 6. 19. 21:27
반응형

_method를 정의하기 위해 인수를 전달하는 방법은 무엇입니까?

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에서 이중 스플랫을 도입했습니다.**( 개의 별) 다음과 같은 일을 합니다.

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}

키워드 인수, 스플랫 및 이중 스플랫이 모두 하나로 된 예제를 만들려고 했습니다.

 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은 "남은 모든 키워드 인수를 캡처"하는 것이므로 이들을 혼합하면 예상된 논리가 깨집니다.(저는 이 점을 증명할 어떠한 참고 자료도 가지고 있지 않습니다. doh!)

2018년 8월 업데이트:

요약 기사: https://blog.eq8.eu/til/metaprogramming-ruby-examples.html

케빈 코너의 답변 외에도: 블록 인수는 메서드 인수와 동일한 의미를 지원하지 않습니다.기본 인수 또는 차단 인수는 정의할 수 없습니다.

이것은 전체 메서드 인수 의미론을 지원하는 새로운 대체 "stabby lambda" 구문을 사용하여 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

언급URL : https://stackoverflow.com/questions/89650/how-do-you-pass-arguments-to-define-method

반응형