zoukankan      html  css  js  c++  java
  • 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"}]
  • 相关阅读:
    camke 参数
    17.计算1-100之和+1-50的平方和+1-10的倒数
    16.求Sn=a+aa+aaa+aaaa.......之值
    15.计算1!+2!+3!+.....20!=?
    14.输出所有的“水仙花”
    13.企业发放的奖金根据利润提成
    12.输入一个成绩计算其A,B,C,D,E等级
    11.键盘输入小于1000的整数
    10.求方程的根
    2019考研历程回顾
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5449010.html
Copyright © 2011-2022 走看看