将嵌套函数内部的Ruby转换为Node.js [英] Converting Ruby's yield inside of nested functions into Node.js

查看:97
本文介绍了将嵌套函数内部的Ruby转换为Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一部分Ruby代码转换为Node.js.关于yield,我遇到了一件特别的事.代码如下:

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

如果我正确阅读此代码,则表示迭代哈希属性.对于每个元素,调出外部函数并使用给定的p["key"], p["value"], p值执行操作."

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."

我真的无法理解Java脚本的外观.我熟悉编写更多琐碎的闭包.完全有可能进行转换吗?我猜是这样的:

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...

推荐答案

否,可以的翻译.这有点欺骗性,因为可以使用隐式块来调用ruby中的任何方法.如果在那里,您可以yield.如果您暂时不使用它们,它就是其中的一种速记技巧:)

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 :)

在ruby版本中,您还可以添加&block参数并将yield(...替换为block.call(....在功能上是等效的.

In the ruby version, you could also add a &block argument and replace yield(... with block.call(.... It'd be functionally equivalent.

这篇关于将嵌套函数内部的Ruby转换为Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆