each-Select
2016-04-30 17:03
417 查看
While Ruby’s
For the next few examples, we’ll work with a slightly more complex data structure. It look like this:
the block returned
We can use
Because the block is so short, it would also work well as a one-liner:
That line returns either
This table shows each step of the process:
At the very end,
eachmethod 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" } ]
selectis similar to
eachin that we pass it a block to run on each element in the collection, but the similarities stop there. The important difference is that
selectwill return a new collection with only the items that
the block returned
truefor. It sounds pretty intimidating at first, so let’s walk through an example.
We can use
selectto 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"}
selectwill 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
trueor
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,
selectreturns this Array which we save to a new
online_friendsvariable:
[{ name: "Diego", status: "Online"}, { name: "Gloria", status: "Online"}]
相关文章推荐
- 《有关SDL的简介》
- 这1个月自己技术上的成长
- 1028. 人口普查(20)
- 将ubuntu14.04 从mysql从5.5删除之后安装5.7遇到的一些问题(本篇不讨论热升级)
- Android切换横屏竖屏生命周期变化
- poj3415 Common Substrings (后缀数组+单调队列)
- 理解不同特征值的特征向量之间的非线性关系
- Caffe学习系列(3):im2col
- 一些小感悟
- Linux 系统默认运行级别设定
- poj2226 二分图匹配经典行列建图
- 1027. 打印沙漏(20)
- 记录最近遇到的两个小问题
- nyoj_71 独木舟上的旅行
- redis数据类型
- 【小笨鸟看JDK1.7集合源码之四】Vector源码剖析
- 机器学习----Softmax回归
- hdu_2608_0 or 1_数论
- ListView和数据适配器SimpleAdapter例子
- hdu_2608_0 or 1_数论