ruby 数组删除部分数组_您需要了解的六个Ruby数组方法

ruby 数组删除部分数组

Arrays are one of the fundamental structures of programming. Being able to quickly manipulate and read data out of them is vital to success in building stuff with computers. Here are six methods you can’t do without.

数组是编程的基本结构之一。 能够快速操纵和读取其中的数据对于成功构建计算机至关重要。 这是您不能没有的六种方法。

地图/每个 (Map/Each)

These two methods are very similar. They allow you to step through “each” item in an array and do something to it.

这两种方法非常相似。 它们允许您单步执行数组中的“每个”项目并对其执行操作。

Check out some code:

查看一些代码:

array = [1, 2, 3]
effects = array.each{|x| # create record from x }
added = array.map{ |x| x + 2 }

If we read from added, we’ll get [3, 4, 5]. If we read from effects, we’ll still get [1, 2, 3]. Here’s the difference between these two: .map will return a new modified array, whereas .each will return the original array.

如果从added读取,我们将得到[3, 4, 5] 。 如果从effects读取,我们仍然会得到[1, 2, 3] 。 这是两者之间的区别: .map将返回一个新的修改后的数组,而.each将返回原始的数组。

地图中的副作用 (Side effects in map)

If you’re used to functional programming, Ruby’s .map might seem very strange. Look at this example. I have a simple Event class in my project:

如果您习惯了函数式编程,那么Ruby的.map可能看起来很奇怪。 看这个例子。 我的项目中有一个简单的Event类:

# we create an array of records
2.3.0 :025 > array = [e, e2, e3]
 => [#<Event id: 1, name: nil>, #<Event id: 2, name: nil">, #<Event id: 3, name: nil>]
# so far so good
2.3.0 :026 > new_array = array.map{|e| e.name = "a name"; e}
 => [#<Event id: 1, name: "a name">, #<Event id: 2, name: "a name">, #<Event id: 3, name: "a name">]
# uh-oh, that ain't right
2.3.0 :027 > array
 => [#<Event id: 1, name: "a name">, #<Event id: 2, name: "a name">, #<Event id: 3, name: "a name">]

We might expect that we are working with some kind of copy of our records in the array, but we are not. That is all just to say: be careful. You can easily create side effects in your .map functions.

我们可能希望我们正在处理数组中记录的某种副本,但事实并非如此。 这只是说:小心。 您可以在.map函数中轻松创建副作用。

Ok rest easy, that was the hard one. Smooth sailing from here on out.

好吧,轻松一点,那是艰难的。 从这里开始航行顺畅。

选择 (Select)

.select allows you to “find” an element in an array. You have to give .select a function that returns true or false, so it knows whether or not to “keep” an array element.

.select允许您“查找”数组中的元素。 您必须给.select一个返回true或false的函数,以便它知道是否“保留”一个数组元素。

2.3.0 :028 > array = ['hello', 'hi', 'goodbye']
2.3.0 :029 > array.select{|word| word.length > 3}
 => ["hello", "goodbye"]

A slightly more complex example, probably getting closer to how you’d actually use this. Let’s throw in .map at the end for good measure:

一个稍微复杂的示例,可能更接近于您实际使用它的方式。 让我们在末尾添加.map来进行很好的测量:

2.3.0 :030 > valid_colors = ['red', 'green', 'blue']
2.3.0 :031 > cars = [{type: 'porsche', color: 'red'}, {type: 'mustang', color: 'orange'}, {type: 'prius', color: 'blue'}]
2.3.0 :032 > cars.select{ |car| valid_colors.include?(car[:color]) }.map{ |car| car[:type]}
=> ["porsche", "prius"]

Yes, folks, you can join these methods to wield unimaginable power. Ok, you can probably imagine it, but it’s still cool.

是的,伙计们,您可以加入这些方法以发挥不可思议的力量。 好的,您可能可以想象,但是仍然很酷。

更清晰的语法:.map(&:method) (Even cleaner syntax: .map(&:method))

If we had been working with car objects and not just a simple hash, we could have used a cleaner syntax. I’ll use a different example for brevity. Maybe we are preparing this list of cars to send out in an API and need to generate JSON. We can use the .to_json method:

如果我们一直在处理汽车对象,而不仅仅是一个简单的哈希,那么我们可以使用更简洁的语法。 为了简洁起见,我将使用另一个示例。 也许我们正在准备要通过API发送并需要生成JSON的汽车清单。 我们可以使用.to_json方法:

# using regular map syntax
2.3.0 :047 > cars.select{ |car| valid_colors.include?(car[:color]) }.map{|car| car.to_json}
 => ["{\"type\":\"porsche\",\"color\":\"red\"}", "{\"type\":\"prius\",\"color\":\"blue\"}"]
# using the cleaner syntax
2.3.0 :046 > cars.select{|car| valid_colors.include?(car[:color]) }.map(&:to_json)
 => ["{\"type\":\"porsche\",\"color\":\"red\"}", "{\"type\":\"prius\",\"color\":\"blue\"}"]

拒绝 (Reject)

Reject is the yin to .select's yang:

Reject是.select的yang的阴:

2.3.0 :048 > cars.reject{|car| valid_colors.include?(car[:color]) }.map{|car| car[:type]}
 => ["mustang"]

Instead of selecting for the array items we want, we will reject everything that does not make our function return true. Remember that the function inside our reject is what determines if the array item will be returned or not — if it’s true, the item is returned, otherwise not.

而不是选择所需的数组项,我们将拒绝所有不会使函数返回true的内容。 请记住, 拒绝中的函数是确定是否要返回数组项的函数 -如果为true,则返回该项,否则返回。

减少 (Reduce)

Reduce has a more complex structure than our other array methods, but it’s generally used for pretty simple things in Ruby — mostly math stuff. We’ll take an array, then run a function on every item in that array. This time, we care about what is being returned from the other array items. Typically we are adding up a bunch of numbers:

与我们的其他数组方法相比,Reduce具有更复杂的结构,但是它通常用于Ruby中非常简单的事情-主要是数学方面的东西。 我们将获取一个数组,然后对该数组中的每个项目运行一个函数。 这次,我们关心其他数组项返回的内容。 通常,我们将一堆数字相加:

2.3.0 :049 > array = [1, 2, 3]
2.3.0 :050 > array.reduce{|sum, x| sum + x}
 => 6

Note that we can work with strings in the same way:

请注意,我们可以以相同的方式使用字符串:

2.3.0 :053 > array = ['amber', 'scott', 'erica']
2.3.0 :054 > array.reduce{|sum, name| sum + name}
 => "amberscotterica"

This might be helpful if we are looking at a bunch of work records. If we need to add up total hours worked, or if we want to find out the sum of all donations last month. One final note about .reduce. If you’re working with anything other than regular old numbers (or strings), you’ll need to include a starting value as an argument:

如果我们查看大量工作记录,这可能会有所帮助。 如果我们需要加总工作时间,或者想要找出上个月所有捐款的总和。 关于.reduce.最后一点说明.reduce. 如果您要使用常规旧数字(或字符串)以外的其他任何东西,则需要包含一个起始值作为参数:

array = [{weekday: 'Monday', pay: 123}, {weekday: 'Tuedsay', pay: 244}]
array.reduce(0) {|sum, day| sum + day[:pay]}
 => 367
array.reduce(100) {|sum, day| sum + day[:pay]}
 => 467

There are, of course, more advanced ways to use .reduce but this is plenty to get you started.

当然,还有使用.reduce更高级的方法,但这足以帮助您入门。

加入 (Join)

I’m throwing in .join as a bonus because it’s so dang useful. Let’s use our cars again:

我把.join作为奖励,因为它很有用。 让我们再次使用我们的汽车:

2.3.0 :061 > cars.map{|car| car[:type]}.join(', ')
 => "porsche, mustang, prius"

.join is a lot like .reduce except it’s got a super-clean syntax. It takes one argument: a string that will be inserted between all array elements. .joincreates one long string out of whatever you give it, even if your array is a bunch of non-string stuff:

.join.reduce很像,只是它具有超纯净的语法。 它带有一个参数:一个将在所有数组元素之间插入的字符串。 .join根据您提供的内容创建一个长字符串,即使您的数组是一堆非字符串的东西也是如此:

2.3.0 :062 > cars.join(', ')
 => "{:type=>\"porsche\", :color=>\"red\"}, {:type=>\"mustang\", :color=>\"orange\"}, {:type=>\"prius\", :color=>\"blue\"}"
2.3.0 :065 > events.join(', ')
 => "#<Event:0x007f9beef84a08>, #<Event:0x007f9bf0165e70>, #<Event:0x007f9beb5b9170>"

为什么不把它们全部放在一起 (Why not just throw it all together)

Let’s use all of the array methods in this post together! Ten days of chores, and it’s random how long each will take. We want to know the total time we’ll spend on chores. This is assuming we slack off and ignore everything that takes longer than 15 minutes. Or put off until another day anything that can be done in less than 5:

让我们一起使用本文中的所有数组方法! 十天的琐事,而且随机需要多长时间。 我们想知道我们花在杂务上的总时间。 这是假设我们懈怠并忽略了所有耗时超过15分钟的事情。 或推迟不到5天将所有事情推迟到第二天:

days = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
days.map{|day| day.odd? ? 
  {task: 'dishes', minutes: Random.rand(20)} :
  {task: 'sweep', minutes: Random.rand(20)}}
  .select{|task| task[:minutes] < 15}
  .reject{|task| task[:minutes] < 5}
  .reduce(0) {|sum, task| sum + task[:minutes]}

My answer is irrelevant because you’ll get different random minutes for your tasks to take. If any of this is fresh or confusing, fire up a Ruby console and give it a whirl.

我的回答是无关紧要的,因为您将获得不同的随机分钟来执行任务。 如果这是新鲜的或令人困惑的,请启动Ruby控制台并进行旋转。

PS: That ? : business on .map is called a ternary. It’s just an if-else statement. I’m only using it here to be fancy and get everything on “one” line. You should avoid such a complicated ternary in your own code base.

PS:那? : ? : .map上的业务称为ternary 。 这只是一个if-else语句。 我仅在这里使用它是为了使所有内容都保持一致。 您应该在自己的代码库中避免使用如此复杂的三元数。

See you next time!

下次见!

翻译自: https://www.freecodecamp.org/news/six-ruby-array-methods-you-need-to-know-5f81c1e268ce/

ruby 数组删除部分数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值