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.pswp.cn/news/394915.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394915.shtml
英文地址,請注明出處:http://en.pswp.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;以下是我之前在"云和恩墨大講堂”分享過的一個案…