다른 사람들이 말했듯이 루비에서이 작업을 수행하는 다른 방법이 있습니다. 다만 호기심이 있다면 Ruby에서 파이썬 접근법과 동등합니다 (메서드 이름을 결정하면 Object#send 사용).
h = MyHandler.new
h.handle 'test', 'example'
h.handle 'other', 'example'
h.handle 'missing', 'example'
을 출력은 다음과 같습니다 :
class MyHandler
def handle_test(arg)
puts "handle_test called with #{arg}"
end
def handle_other(arg)
puts "handle_other called with #{arg}"
end
def handle(type, *args)
method_name = "handle_#{type}"
if respond_to? method_name
send(method_name, args)
else
raise "No handler method for #{type}"
end
end
end
당신은 할 수
handle_test called with example
handle_other called with example
handle.rb:15:in `handle': No handler method for missing (RuntimeError)
from handle.rb:23
Ruby에는 대소 문자가 있습니다. 왜 이걸하고 싶어? –
그 무엇보다 호기심이 더 많습니다 :) – RailsSon
한 언어에서 다른 언어로 코드를 변환 할 때 새로운 언어에 대해 새 코드를 관용적으로 작성하는 것이 좋습니다. 다른 말로하면, 다른 언어의 구조를 무차별 적으로 강제하는 대신에 그 구조를 이용하십시오. 이 특별한 경우에, 루비의'Object # send'가 그것을 할 것입니다,하지만 나는 코드 가독성과 유지 보수를 위해서'case/when' 문을 사용하는 것이 더 나을 것이라고 생각합니다. 그들은 당신이 뭔가를 추가해야 할 때 일년 후 지불 할 일이 무엇인지 쉽게 보게합니다. –