问题
I'm trying to convert a chunk of Ruby code into Node.js. One particular piece has me stumped, concerning yield
. The code goes like this:
each_pair(hash["args"][0]) do |key, value, pair|
# perform operations
end
...
def each_pair(hash)
hash["props"].each do |p|
yield(p["key"], p["value"], p)
end
end
If I am reading this code correctly, it's saying "Iterate over the hash properties. For every element, call back out to the outer function and perform the operation with the given p["key"], p["value"], p
values."
I can't really comprehend how this would look in Javascript. I'm acquainted with writing more trivial closures. Is a conversion possible at all? I'm guessing it's something like:
each_pair(hash["args"][0], function(key, value, pair) {
// perform operations
}
...
function each_pair(hash, func) {
hash["props"].forEach(p) {
func(p["key"], p["value"], p)
}
}
But something doesn't feel right...
回答1:
No, that's an OK translation. It's a little deceptive because any method in ruby can be called with an implicit block. If it's there, you can yield
it. It's one of those shorthand tricks that you forget if you don't use them for a while :)
In the ruby version, you could also add a &block
argument and replace yield(...
with block.call(...
. It'd be functionally equivalent.
来源:https://stackoverflow.com/questions/12490812/converting-rubys-yield-inside-of-nested-functions-into-node-js