select ...as_一起使用.select .map和.reduce方法可充分利用Ruby

select ...as

by Declan Meehan

由Declan Meehan

一起使用.select .map和.reduce方法可充分利用Ruby (Get the most out of Ruby by using the .select .map and .reduce methods together)

You should absolutely never ever repeat yourself when writing code. In other words, do not repeat yourself twice. To be clear — do not write something which has been explained already.

编写代码时,绝对绝对不要重复自己。 换句话说,不要重复自己两次。 要清楚—不要写已经解释过的内容。

This is called tautology, and when writing code it should be avoided at all times. For instance, wouldn’t it have been nice instead of reading this lengthy paragraph if I just used the three powerful words “never, repeat, yourself”?

这称为重言式,在编写代码时应始终避免。 例如,如果我只使用三个功能强大的词“永不重复,自己动手”,那不是阅读这段冗长的段落会很好吗?

Well that’s what I’m going to show you how to do with Ruby’s .select .map and .reduce(or .inject) methods.

好的,这就是我将向您展示如何使用Ruby的.select .map和.reduce(或.inject)方法的方法。

(Example)

Let’s suppose you are looking at a dictionary full of employee’s names, job titles, and salaries. Let’s also imagine that you wanted to find out the total amount that the company was spending on developers’ salaries. Now, without using a single method in Ruby, you would most likely write your code out something like this:

假设您正在看一本字典,里面有雇员的姓名,职称和薪水。 我们还假设您想找出公司在开发人员薪金上花费的总额。 现在,无需在Ruby中使用单个方法,您很可能会编写出如下代码:

people = [{first_name: "Gary", job_title: "car enthusiast", salary: "14000" },  {first_name: "Claire", job_title: "developer", salary: "15000"},  {first_name: "Clem", job_title: "developer", salary: "12000"}
]
person1 = people[0][:job_title]
person2 = people[1][:job_title]
person3 = people[2][:job_title]
total = 0
if person1 == "developer"total += people[0][:salary].to_i
end
if person2 == "developer"total += people[1][:salary].to_i
end
if person3 == "developer"total += people[2][:salary].to_i
end
puts total

Wow — that is a lot of lines to write to find only three people. Imagine if the company employed hundreds of people!

哇,写很多行才能找到三个人。 想象一下,如果公司雇用了数百名员工!

Now if you know a bit about loops, then the next easiest step would be to write an each method to put all the salaries together. This might only take up five or six lines but check this out!

现在,如果您对循环有所了解,那么下一个最简单的步骤将是编写一个each方法来将所有薪水放在一起。 这可能只占用五或六行,但请检查一下!

puts people.select{|x| x[:job_title] == "developer"}.map{|y| y[:salary].to_i}.reduce(:+)

You’ll notice every method begins and ends with a curly bracket. This can be used instead of the do and end commands if it is a single line block.

您会注意到每种方法都以大括号开头和结尾。 如果它是单个行块,则可以使用它代替do和end命令。

{} == (do end) #for single-line blocks only

。选择 (.select)

Let’s start with the .select method. We create a variable (x) and iterate over every method in the people array. It then checks with a boolean expression if the key of (:job_title) is equal to the “developer” string. If the boolean returns true, then the select method places the hash that returned true into a new object.

让我们从.select方法开始。 我们创建一个变量(x)并遍历people数组中的每个方法。 然后,它使用布尔表达式检查(:job_title)的键是否等于“开发人员”字符串。 如果布尔值返回true,则select方法将返回true的哈希值放入新对象。

。地图 (.map)

The map method is used for creating a new array that does not affect the array it is looping through. I used this method to create a new variable (y), and then used that variable to grab the value of the key (:salary). Then, finally, I turned that value from a string into an integer.

map方法用于创建一个新数组,该数组不会影响正在循环通过的数组。 我使用此方法创建了一个新变量(y),然后使用该变量来获取键(:salary)的值。 然后,最后,我将该值从字符串转换为整数。

。减少 (.Reduce)

This one probably looks the most confusing so let's expand it a bit.

这个看起来可能最令人困惑,所以让我们扩展一下。

.reduce(0){|sum, indv| sum + indv} #is the same as .reduce(:+)

The reduce method creates a new variable which you set the value equal to in the first parentheses (0). You then create two new values (sum and indv) of which one is the sum that you add the individual salaries to.

reduce方法将创建一个新变量,您可以在第一个括号(0)中将该值设置为等于。 然后,您创建两个新值(sum和indv),其中一个是您将各个薪金相加的总和。

I hope that explains it well! Please let me know if you have any questions.

我希望这能很好地解释! 请让我知道,如果你有任何问题。

翻译自: https://www.freecodecamp.org/news/ruby-using-the-select-map-and-reduce-methods-together-a9b2af30804b/

select ...as

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394915.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一些书单

仅对近来的学习做些回顾吧 学习永无止境--> 2015年已完成书单: 文学: 硅谷之火浪潮之巅天才在左疯子在右从0到1生命咖啡馆黑客与画家奇思妙想:15位计算机天才及其重大发现乔布斯传平凡的世界(三部全)一只iphone的全…

oracle 11gogg,【OGG】Oracle GoldenGate 11g (二) GoldenGate 11g 单向同步配置 上

Oracle GoldenGate 11g (二)GoldenGate 11g 单向同步配置 上ItemSource SystemTarget SystemPlatformRHEL6.4 - 64bitRHEL6.4 - 64bitHostnamerhel64.oracle.comora11g.oracle.comDatabaseOracle 11.2.0.3Oracle 11.2.0.3Character SetAL32UTF8AL32UTF8ORACLE_SIDPRODEMREPList…

今天听说了一个压缩解压整型的方式-group-varint

group varint https://github.com/facebook/folly/blob/master/folly/docs/GroupVarint.md 这个是facebook的实现 https://www.slideshare.net/parallellabs/building-software-systems-at-google-and-lessons-learned/48-Group_Varint_Encoding_Idea_encode

Centos7-卸载自带的jdk 安装jdk8

卸载JDK Centos7一般都会带有自己的openjdk,我们一般都回用oracle的jdk,所以要卸载 步骤一:查询系统是否以安装jdk #rpm -qa|grep java 或 #rpm -qa|grep jdk 或 #rpm -qa|grep gcj 步骤二:卸载已安装的jdk #rpm -e --nodeps java-1.8.0-openjdk…

小猪佩奇python_python画个小猪佩奇

#!/usr/bin/python #-*- coding: utf-8 -*-import turtleast def nose(x,y):#鼻子 t.pu() t.goto(x,y) t.pd() t.seth(-30) t.begin_fill() a0.4 for i in range(120):if 0<i<30 or 60<i<90: aa0.08t.lt(3) #向左转3度 t.fd(a) #向前走a的步长else: aa-0.08t.lt(3)…

javascript 符号_理解JavaScript中“ =”符号的直观指南

javascript 符号by Kevin Kononenko凯文科诺年科(Kevin Kononenko) 理解JavaScript中“ ”符号的直观指南 (A Visual Guide to Understanding the “” Sign in JavaScript) 实际上&#xff0c;对于第一次学习编码的人来说&#xff0c;赋值运算符(或“ ”符号)实际上会产生误导…

iOS开发UIScrollView的底层实现

起始 做开发也有一段时间了&#xff0c;经历了第一次完成项目的激动&#xff0c;也经历了天天调用系统的API的枯燥&#xff0c;于是就有了探索底层实现的想法。 关于scrollView的思考 在iOS开发中我们会大量用到scrollView这个控件&#xff0c;我们使用的tableView/collectionv…

oracle查看登录时间黑屏,oracle 11g默认用户名、密码解锁 以及安装后重启黑屏问题.doc...

oracle 11g默认用户名、密码解锁 以及安装后重启黑屏问题.doc还剩3页未读&#xff0c;继续阅读下载文档到电脑&#xff0c;马上远离加班熬夜&#xff01;亲&#xff0c;喜欢就下载吧&#xff0c;价低环保&#xff01;内容要点&#xff1a;遇的同学&#xff0c;参考一下解决办法…

第六十二节,html分组元素

html分组元素 学习要点&#xff1a; 1.分组元素总汇 2.分组元素解析 本章主要探讨HTML5中分组元素的用法。所谓分组&#xff0c;就是用来组织相关内容的HTML5元素&#xff0c;清晰有效的进行归类。 一&#xff0e;分组元素总汇 为了页面的排版需要&#xff0c;HTML5提供了几种语…

WebSocket 实战--转

原文地址&#xff1a;http://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/ WebSocket 前世今生 众所周知&#xff0c;Web 应用的交互过程通常是客户端通过浏览器发出一个请求&#xff0c;服务器端接收请求后进行处理并返回结果给客户端&#xff0c;客户端浏览器将信息呈…

python图形化编程更改内部参数_python-参数化-(3)(替换数据)

一.在读取excel文件、其他数据来源会遇到一些无法转换或者特殊标记的字符串等&#xff0c;不能直接使用。这时候需要对数据进行处理&#xff0c;替换为自己需要的数据进行下一步操作&#xff0c;如下&#xff1a; 替换 1.replace() str.replace(old,new[,max]) old -- 将被替换…

css grid布局_如何使用CSS Grid重新创建Medium的文章布局

css grid布局When people think of CSS Grid they normally envision image grid layouts and full web pages. However, CSS Grid is actually a superb technology for laying out articles as well, as it allows you to do things which previously was tricky to achieve.…

2017视频监控行业应用趋势与市场发展分析

安防行业的发展&#xff0c;从传统单一的业务形态到业务多元化与国际化的转变&#xff0c;是社会安全需求变化与视频监控技术双向驱动的结果。在新的行业生态体系下&#xff0c;传统监控技术与新兴技术的融合&#xff0c;跨行业的业务协同&#xff0c;以及以客户为中心的产业形…

oracle 11.2.4联机文档,ORACLE 11G 联机文档partition_extended_name的一个错误

在看11G联机文档的PARTITION EXTENDED NAME限制的时候&#xff0c;测试发现与书上描述不符。Restrictions on Extended Names Currently, the use of partition-extended and subpartition-extended table names has the following restrictions:No remote tables: A partition…

mongodb 安装、启动

MongoDB 之 你得知道MongoDB是个什么鬼 MongoDB - 1 最近有太多的同学向我提起MongoDB,想要学习MongoDB,还不知道MongoDB到底是什么鬼,或者说,知道是数据库,知道是文件型数据库,但是不知道怎么来用 那么好,所谓千呼万唤始出来,现在我就拉给你们看: 一.初识MongoDB 之 什么东西都…

python os path_python os.path模块

os.path.abspath(path) #返回绝对路径 os.path.basename(path) #返回文件名 os.path.commonprefix(list) #返回list(多个路径)中&#xff0c;所有path共有的最长的路径。 os.path.dirname(path) #返回文件路径 os.path.exists(path) #路径存在则返回True,路径损坏返回False os.…

[转载]PSCAD调用MATLAB/SIMULINK之接口元件设计

原文地址&#xff1a;PSCAD调用MATLAB/SIMULINK之接口元件设计作者&#xff1a;luckyhappier1)接口元件 接口元件包括Graphics&#xff0c;Parameters和Script。注意&#xff1a;变量要与DSDYN要一致&#xff08;PSCAD根据变量名区别变量&#xff09;。 2&#xff09;Circuit 定…

css flexbox模型_Flexbox教程:了解如何使用CSS Flexbox编写响应式导航栏

css flexbox模型In this article, I’ll explain how to create a navbar which adapts to various screen sizes using Flexbox along with media queries.在本文中&#xff0c;我将解释如何使用Flexbox和媒体查询来创建适应各种屏幕尺寸的导航栏。 This tutorial can also b…

oracle数字类型ef映射,Entity Framework 学习中级篇5—使EF支持Oracle9i - ♂风车车.Net - 博客园...

从Code MSDN上下载下来的EFOracleProvider不支持Oracle9i.但是,目前我所使用的还是Oracle9i。为此,对EFOracleProvider修改了以下&#xff0c;以便使其支持Oracle9i.下面说说具体修改地方.(红色部分为添加或修改的代码部分)一&#xff0c;修改EFOracleProvider1,修改EFOraclePr…

Oracle 数据库之最:你见过最高的 SQL Version 是多少?

Oracle数据库中执行的SQL&#xff0c;很多时候会因为种种原因产生多个不同的执行版本&#xff0c;一个游标的版本过多很容易引起数据库的性能问题&#xff0c;甚至故障。 有时候一个SQL的版本数量可能多达数万个&#xff0c;以下是我之前在"云和恩墨大讲堂”分享过的一个案…