루비에서 send ()는 무엇을합니까?
누군가 나에게 무엇을 말해 줄 수 있습니까?
send("#{Model.find...}")
이고 무엇입니까?
send
일부 메서드가 반응 할 때까지 (이름이 첫 번째 인수와 일치하기 때문에) 클래스 계층 구조의 객체 인스턴스와 조상에게 메시지를 보냅니다.
실질적으로이 라인은 동일합니다.
1.send '+', 2
1.+(2)
1 + 2
send
가시성 검사 를 우회하므로 개인 메서드도 호출 할 수 있습니다 (단위 테스트에 유용함).
보내기 전에 실제로 변수가 없으면 전역 개체가 사용됨을 의미합니다.
send :to_s # "main"
send :class # Object
send 는 이름으로 다른 메소드를 호출 할 수있는 루비 (레일 없음) 메소드입니다.
문서에서
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
http://corelib.rubyonrails.org/classes/Object.html#M001077
.send 메소드로 생각하는 가장 유용한 기능 중 하나는 동적으로 메소드를 호출 할 수 있다는 것입니다. 이것은 많은 타이핑을 절약 할 수 있습니다. .send 메서드의 가장 널리 사용되는 용도 중 하나는 속성을 동적으로 할당하는 것입니다. 예를 들면 :
class Car
attr_accessor :make, :model, :year
end
정기적으로 속성을 할당하려면
c = Car.new
c.make="Honda"
c.model="CRV"
c.year="2014"
또는 .send 방법 사용 :
c.send("make=", "Honda")
c.send("model=", "CRV")
c.send("year=","2014")
그러나 모두 다음으로 대체 할 수 있습니다.
Rails 앱이 사용자 입력에서 자동차 클래스에 속성을 할당해야한다고 가정하면 다음을 수행 할 수 있습니다.
c = Car.new()
params.each do |key, value|
c.send("#{key}=", value)
end
Antonio Jha의 https://stackoverflow.com/a/26193804/1897857 과 유사한 또 다른 예
객체에 대한 속성을 읽어야하는 경우입니다.
예를 들어 문자열 배열이있는 경우 문자열을 반복하고 개체에서 호출하면 작동하지 않습니다.
atts = ['name', 'description']
@project = Project.first
atts.each do |a|
puts @project.a
end
# => NoMethodError: undefined method `a'
그러나 다음과 send
같이 객체에 문자열을 지정할 수 있습니다 .
atts = ['name', 'description']
@project = Project.first
atts.each do |a|
puts @project.send(a)
end
# => Vandalay Project
# => A very important project
보내기는 무엇을합니까?
send
메서드를 호출하는 또 다른 방법입니다.
This is best illustrated by example:
o = Object.new
o.send(:to_s) # => "#<Object:0x00005614d7a24fa3>"
# is equivalent to:
o.to_s # => "#<Object:0x00005614d7a24fa3>"
Send lives in the Object class.
What is the benefit of ths?
The benefit of this approach is that you can pass in the method you want to call as a parameter. Here is a simple example:
def dynamically_call_a_method(name)
o = Object.new
o.send name
end
dynamically_call_a_method(:to_s) # => "#<Object:0x00005614d7a24fa3>"
You can pass in the method you want to be called. In this case we passed in :to_s
. This can be very handy when doing ruby metaprogramming, because this allows us to call different methods according to our different requirements.
Another use case for views:
<%= link_to
send("first_part_of_path_{some_dynamic_parameters}_end_path",
attr1, attr2), ....
%>
Allow . you to write scalable view who work with all kind of objects with:
render 'your_view_path', object: "my_object"
참고URL : https://stackoverflow.com/questions/3337285/what-does-send-do-in-ruby
'program story' 카테고리의 다른 글
ES6 구문을 사용하여 onclick 이벤트를 통해 매개 변수를 전달하는 반응 (0) | 2020.09.20 |
---|---|
GDB가 줄 사이를 예측할 수없이 점프하고 변수를“ (0) | 2020.09.20 |
비어 있거나 값이없는 문자열 테스트 (0) | 2020.09.20 |
이보기는 제한되지 않습니다. (0) | 2020.09.20 |
설치 오류 : INSTALL_PARSE_FAILED_MANIFEST_MALFORMED? (0) | 2020.09.20 |