在 Ruby 中计算导数 ([i] - [i - 1])

发布于 2024-07-30 01:17:54 字数 221 浏览 2 评论 0原文

使用 for 循环或each_with_index 很简单,只是想知道是否有更好的方法使用 Ruby 语法来做到这一点。

我需要创建一个新数组,它是源数组的导数,例如:

for(int i = 1; i < oldArray.length; i++)
{
    newArray[i] = oldArray[i] - oldArray[i-1]
}

Trivial using a for loop or each_with_index, just wondering if there was a better way of doing it using Ruby syntax.

I need to create a new array that is the derivative of the source array, eg:

for(int i = 1; i < oldArray.length; i++)
{
    newArray[i] = oldArray[i] - oldArray[i-1]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她如夕阳 2024-08-06 01:17:54
old_array.each_cons(2).map{|x, y| y - x}

使用块大小为 2 但没有块的情况调用 Enumerable#each_cons 会返回一个枚举器,它将迭代 old_array 中的每对连续元素。 然后我们只需使用 map 对每对执行减法。

old_array.each_cons(2).map{|x, y| y - x}

Enumerable#each_cons called with with a chunk size of 2 but without a block returns an Enumerator which will iterate over each pair of consecutive elements in old_array. Then we just use map to perform a subtraction on each pair.

横笛休吹塞上声 2024-08-06 01:17:54
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文