有人可以解释在 Ruby 中注入的真实世界的普通语言用法吗? [英] Can someone explain a real-world, plain-language use for inject in Ruby?

查看:52
本文介绍了有人可以解释在 Ruby 中注入的真实世界的普通语言用法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Ruby,并且遇到了注入.我正处于理解它的风口浪尖,但是当我是那种需要真实世界的例子来学习某些东西的人时.我遇到的最常见的例子是人们使用注入将 (1..10) 范围的总和相加,我不太关心.这是一个随意的例子.

I'm working on learning Ruby, and came across inject. I am on the cusp of understanding it, but when I'm the type of person who needs real world examples to learn something. The most common examples I come across are people using inject to add up the sum of a (1..10) range, which I could care less about. It's an arbitrary example.

在实际程序中我会用它做什么?我正在学习,所以我可以继续使用 Rails,但我不必有一个以网络为中心的例子.我只需要一些有目的的东西,我可以把头包起来.

What would I use it for in a real program? I'm learning so I can move on to Rails, but I don't have to have a web-centric example. I just need something that has a purpose I can wrap my head around.

谢谢大家.

推荐答案

这里有几个 inject() 示例:

[1, 2, 3, 4].inject(0) {|memo, num| memo += num; memo} # sums all elements in array

该示例迭代 [1, 2, 3, 4] 数组的每个元素,并将元素添加到 memo 变量(memo 通常用作块变量名称).此示例在每次迭代后显式返回 memo,但返回也可以是隐式的.

The example iterates over every element of the [1, 2, 3, 4] array and adds the elements to the memo variable (memo is commonly used as the block variable name). This example explicitly returns memo after every iteration, but the return can also be implicit.

[1, 2, 3, 4].inject(0) {|memo, num| memo += num} # also works

inject() 在概念上类似于以下显式代码:

inject() is conceptually similar to the following explicit code:

result = 0
[1, 2, 3, 4].each {|num| result += num}
result # result is now 10

inject() 也可用于创建数组和散列.下面是如何使用inject()将[['dogs', 4], ['cats', 3], ['dogs', 7]] 转换为{'dogs'=>11, '猫' =>3}.

inject() is also useful to create arrays and hashes. Here is how to use inject() to convert [['dogs', 4], ['cats', 3], ['dogs', 7]] to {'dogs' => 11, 'cats' => 3}.

[['dogs', 4], ['cats', 3], ['dogs', 7]].inject({'dogs' => 0, 'cats' => 0}) do |memo, (animal, num)|
  memo[animal] = num
  memo
end

这是一个更通用和优雅的解决方案:

Here is a more generalized and elegant solution:

[['dogs', 4], ['cats', 3], ['dogs', 7]].inject(Hash.new(0)) do |memo, (animal, num)|
  memo[animal] = num
  memo
end

同样,inject() 在概念上类似于以下代码:

Again, inject() is conceptually similar to the following code:

result = Hash.new(0)
[['dogs', 4], ['cats', 3], ['dogs', 7]].each do |animal, num|
  result[animal] = num
end
result # now equals {'dogs' => 11, 'cats' => 3}

这篇关于有人可以解释在 Ruby 中注入的真实世界的普通语言用法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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