문제

이와 같은 레일 도우미 파일에 메소드가 있습니다.

def table_for(collection, *args)
 options = args.extract_options!
 ...
end

그리고 나는이 방법을 이렇게 부를 수 있기를 원합니다.

args = [:name, :description, :start_date, :end_date]
table_for(@things, args)

양식 커밋을 기반으로 인수를 동적으로 전달할 수 있도록. 방법을 다시 작성할 수 없습니다. 방법이 너무 많은 곳에서 사용하기 때문에 어떻게해야합니까?

도움이 되었습니까?

해결책

루비는 여러 논쟁을 잘 처리합니다.

여기에 있습니다 꽤 좋은 예입니다.

def table_for(collection, *args)
  p collection: collection, args: args
end

table_for("one")
#=> {:collection=>"one", :args=>[]}

table_for("one", "two")
#=> {:collection=>"one", :args=>["two"]}

table_for "one", "two", "three"
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", "two", "three")
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", ["two", "three"])
#=> {:collection=>"one", :args=>[["two", "three"]]}

(IRB에서 출력 절단 및 붙여 넣기)

다른 팁

이런 식으로 부르십시오.

table_for(@things, *args)

그만큼 splat (*) 연산자는 메소드를 수정하지 않고 작업을 수행합니다.

class Hello
  $i=0
  def read(*test)
    $tmp=test.length
    $tmp=$tmp-1
    while($i<=$tmp)
      puts "welcome #{test[$i]}"
      $i=$i+1
    end
  end
end

p Hello.new.read('johny','vasu','shukkoor')
# => welcome johny
# => welcome vasu
# => welcome shukkoor
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top