배열, 해시 범위의 단일 메서드 _missing
-
11-12-2019 - |
문제
나는 Ruby의 새로운 것입니다.모든 범위, 배열 및 해시 I.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.E.예를 들어,다음은 작동해야합니다 :
[1..5].Sum()
[1,2,3,5].Sum()
{'x' => 1, 'y' = 4}.Sum()
.
sum ()은 메소드 _missing 내부의 사용자 정의 방법 정의 된 입니다.현재 배열, 범위 및 해시에 대한 method_missing을 개별적으로 처리하는 세 가지 기능을 작성했습니다.
해결책
You can define method_missing
for all Enumerables by opening Enumerable
module and adding an instance method to it:
module Enumerable
def method_missing *args
puts 'hi'
end
end
[].hithere # => hi
But I would recommend to define concrete sum
method (starts with lower case letter, according to Ruby methods naming guidelines) instead of adding this logic to method_missing
:
module Enumerable
def sum
# your implementation
end
end
[].sum
다른 팁
As Alex has said the best way would be to just define your own method #sum for Enumerable, however while each Enumerable is supposed to have #each, what it yields is different for each subclass. For example Hash yields a key-value pair, which your single #sum method would have to know how to deal with.
Here's one example of how it might do it, it tries to splat the incoming arguments into an array and the sum includes only the last element of the array. This works for Hashes, Array and Ranges (however it probably only works in 1.9)
module Enumerable
def sum
r = 0
each {|(*x)| r += x.last}
r
end
end
Alternatively you could define your own iterating method for each Enumerable, like #each_for_sum and let #sum use that method to do the summing. But you'd probably have to write several versions of #each_for_sum for different Enumerables (for example, the default #each_for_sum would be just Enumerable#each, but Hash#each_for_sum would yield just values).
module Enumerable
def sum
r = 0
each_for_sum {|x| r += x}
r
end
def each_for_sum &block
each(&block)
end
end
class Hash
def each_for_sum
values.each {|x| yield x}
end
end