each-Select


While Ruby’s each method is useful, it also comes with an awesome extended family of methods that are even more powerful!

For the next few examples, we’ll work with a slightly more complex data structure. It look like this:


friends = [
  {
    name: "Diego",
    status: "Online"
  },
  {
    name: "Liam",
    status: "Away"
  },
  {
    name: "Gloria",
    status: "Online"
  },
  {
    name: "Charlie",
    status: "Away"
  }
]


select is similar to each in that we pass it a block to run on each element in the collection, but the similarities stop there. The important difference is that select will return a new collection with only the items that the block returned true for. It sounds pretty intimidating at first, so let’s walk through an example.

We can use select to create a new Array filled with only our online friends:

online_friends = friends.select do |friend|
  friend[:status] == "Online"
end


Because the block is so short, it would also work well as a one-liner:

online_friends = friends.select{|friend| friend[:status] == "Online"}

select will go through each element one at a time, starting with {name: “Diego”, status: “Online”}, passing it to the block we wrote. The block contains a single line: friend[:status] == “Online”. That line returns either true or false. If the block returns true, that specific item is added to a new Array that will be returned at the very end of select.

This table shows each step of the process:

 
 

At the very end, select returns this Array which we save to a new online_friends variable:

[{ name: "Diego", status: "Online"}, { name: "Gloria", status: "Online"}]









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值