慣用過程模型_慣用的Ruby:編寫漂亮的代碼

慣用過程模型

Ruby is a beautiful programming language.

Ruby是一種美麗的編程語言。

According to Ruby’s official web page, Ruby is a:

根據Ruby的官方網頁,Ruby是:

dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.”

動態的,開放源碼的編程語言為重點的簡單性和工作效率。 它具有優雅的語法,易于閱讀且易于編寫。”

Ruby was created by Yukihiro Matsumoto, a Japanese software engineer. Since 2011, he has been the chief designer & software engineer for Ruby at Heroku.

Ruby由日本軟件工程師Yukihiro Matsumoto創建。 自2011年以來,他一直擔任Heroku Ruby的首席設計師和軟件工程師。

Matsumoto has often said that he tries to make Ruby natural, not simple, in a way that mirrors life.

松本經常說,他試圖一種能反映生活的方式使Ruby自然而不簡單

“Ruby is simple in appearance, but is very complex inside, just like our human body” — Yukihiro Matsumoto
“ Ruby外觀簡單,但是內部卻非常復雜,就像我們的人體一樣” —松本行弘

I feel the same way about Ruby. It is a complex but very natural programming language, with a beautiful and intuitive syntax.

我對Ruby也有同樣的看法。 它是一種復雜但非常自然的編程語言,具有優美而直觀的語法。

With more intuitive and faster code, we are able to build better software. In this post, I will show you how I express my thoughts (aka code) with Ruby, by using snippets of code.

借助更直觀,更快速的代碼,我們可以構建更好的軟件。 在本文中,我將向您展示如何通過代碼片段使用Ruby表達自己的想法(又稱代碼)。

用數組方法表達我的想法 (Expressing my thoughts with array methods)

地圖 (Map)

Use the map method to simplify your code and get what you want.

使用map方法簡化您的代碼并獲得所需的內容。

The method map returns a new array with the results of running a block once for every element in enum.

方法映射將返回一個新數組,并為枚舉中的每個元素運行一次塊。

Let’s try it:

讓我們嘗試一下:

an_array.map { |element| element * element }

Simple as that.

就那么簡單。

But when you begin coding with Ruby, it is easy to always use the each iterator.

但是,當您開始使用Ruby進行編碼時,很容易始終使用每個迭代器。

The each iterator as shown below

每個迭代器如下圖所示

user_ids = []
users.each { |user| user_ids << user.id }

Can be simplified with map in a single beautiful line of code:

可以通過map在一行漂亮的代碼中進行簡化:

user_ids = users.map { |user| user.id }

Or even better (and faster):

甚至更好(更快):

user_ids = users.map(&:id)

選擇 (Select)

And when you’re used to coding with map, sometimes your code can be like this:

當您習慣于使用map進行編碼時,有時您的代碼可能像這樣:

even_numbers = [1, 2, 3, 4, 5].map { |element| element if element.even? } # [ni, 2, nil, 4, nil]
even_numbers = even_numbers.compact # [2, 4]

Using map to select only the even numbers will return the nil object as well. Use the compact method to remove all nil objects.

使用地圖選擇僅偶數將返回 也沒有對象。 使用緊湊方法刪除所有nil對象。

And ta-da, you’ve selected all the even numbers.

ta-da,您已經選擇了所有偶數。

Mission accomplished.

任務完成。

Come on, we can do better than this! Did you hear about the select method from enumerable module?

來吧,我們可以做得更好! 您是否聽說過可枚舉模塊中的select方法?

[1, 2, 3, 4, 5].select { |element| element.even? }

Just one line. Simple code. Easy to understand.

只需一行。 簡單的代碼。 容易理解。

獎金 (Bonus)

[1, 2, 3, 4, 5].select(&:even?)

樣品 (Sample)

Imagine that you need to get a random element from an array. You just started learning Ruby, so your first thought will be, “Let’s use the random method,” and that’s what happens:

想象一下,您需要從數組中獲取隨機元素。 您剛剛開始學習Ruby,因此您的第一個念頭是“讓我們使用隨機方法”,結果如下:

[1, 2, 3][rand(3)]

Well, we can understand the code, but I’m not sure if it is good enough. And what if we use the shuffle method?

好吧,我們可以理解代碼,但是我不確定它是否足夠好。 如果我們使用隨機播放方法怎么辦?

[1, 2, 3].shuffle.first

Hmm. I actually prefer to use shuffle over rand. But when I discovered the sample method, it made so much more sense:

嗯 實際上,我比起rand更喜歡使用shuffle 。 但是,當我發現示例方法時,它變得更加有意義:

[1, 2, 3].sample

Really, really simple.

真的,真的很簡單。

Pretty natural and intuitive. We ask a sample from an array and the method returns it. Now I’m happy.

非常自然和直觀。 我們從數組中請求一個樣本 ,該方法將其返回。 現在我很高興。

What about you?

你呢?

用Ruby語法表達我的想法 (Expressing my thoughts with Ruby syntax)

As I mentioned before, I love the way Ruby lets me code. It’s really natural for me. I’ll show parts of the beautiful Ruby syntax.

如前所述,我喜歡Ruby允許我編寫代碼的方式。 對我來說真的很自然。 我將展示漂亮的Ruby語法的一部分。

隱式回報 (Implicit return)

Any statement in Ruby returns the value of the last evaluated expression. A simple example is the getter method. We call a method and expect some value in return.

Ruby中的任何語句都返回最后一個求值表達式的值。 一個簡單的示例是getter方法。 我們調用一個方法并期望返回一些值。

Let’s see:

讓我們來看看:

def get_user_ids(users)return users.map(&:id)
end

But as we know, Ruby always returns the last evaluated expression. Why use the return statement?

但是,眾所周知,Ruby總是返回最后一個求值表達式。 為什么使用return語句?

After using Ruby for 3 years, I feel great using almost every method without the return statement.

在使用Ruby三年之后,我幾乎可以在沒有return語句的情況下使用幾乎所有方法。

def get_user_ids(users)users.map(&:id)
end

多項作業 (Multiple assignments)

Ruby allows me to assign multiple variables at the same time. When you begin, you may be coding like this:

Ruby允許我同時分配多個變量。 開始時,您可能會像這樣進行編碼:

def values[1, 2, 3]
endone   = values[0]
two   = values[1]
three = values[2]

But why not assign multiple variables at the same time?

但是為什么不同時分配多個變量呢?

def values[1, 2, 3]
endone, two, three = values

Pretty awesome.

太棒了

提出問題的方法(也稱為謂詞) (Methods that ask questions (also called predicates))

One feature that caught my attention when I was learning Ruby was the question mark (?) method, also called the predicates methods. It was weird to see at first, but now it makes so much sense. You can write code like this:

學習Ruby時引起我注意的一個功能是問號(?)方法,也稱為謂詞方法。 一開始看起來很奇怪,但是現在它變得很有道理了。 您可以編寫如下代碼:

movie.awesome # => true

Ok… nothing wrong with that. But let’s use the question mark:

好的,那沒錯。 但是,讓我們使用問號:

movie.awesome? # => true

This code is much more expressive, and I expect the method’s answer to return either a true or false value.

這段代碼更具表現力,我希望方法的答案返回truefalse值。

A method that I commonly use is any? It’s like asking an array if it has anything inside it.

我常用的方法是什么? 這就像詢問數組內部是否有任何東西。

[].any? # => false
[1, 2, 3].any? # => true

插補 (Interpolation)

For me string interpolation is more intuitive than string concatenation. Period. Let’s see it in action.

對我來說,字符串插值比字符串串聯更直觀。 期。 讓我們來看看它的作用。

An example of a string concatenation:

字符串連接的示例:

programming_language = "Ruby"
programming_language + " is a beautiful programming_language" # => "Ruby is a beautiful programming_language"

An example of a string interpolation:

字符串插值的示例:

programming_language = "Ruby"
"#{programming_language} is a beautiful programming_language" # => "Ruby is a beautiful programming_language"

I prefer string interpolation.

我更喜歡字符串插值。

What do you think?

你怎么看?

if語句 (The if statement)

I like to use the if statement:

我喜歡使用if語句:

def hey_ho?true
endputs "let’s go" if hey_ho?

Pretty nice to code like that.

這樣的代碼非常好。

Feels really natural.

感覺真的很自然。

try方法(啟用Rails模式) (The try method (with Rails mode on))

The try method invokes the method identified by the symbol, passing it any arguments and/or the block specified. This is similar to Ruby’s Object#send. Unlike that method, nil will be returned if the receiving object is a nil object or NilClass.

try方法調用由符號標識的方法,并向其傳遞任何參數和/或指定的塊。 這類似于Ruby的Object#send。 不同于方法中,如果接收的對象是nil對象或NilClass 將被返回

Using if and unless condition statement:

使用條件和除非條件語句:

user.id unless user.nil?

Using the try method:

使用try方法:

user.try(:id)

Since Ruby 2.3, we can use Ruby’s safe navigation operator (&.) instead of Rails try method.

從Ruby 2.3開始,我們可以使用Ruby的安全導航運算符(&。)代替Rails try方法。

user&.id

雙管道等于( || =) /備注 (Double pipe equals (||=) / memoization)

This feature is so C-O-O-L. It’s like caching a value in a variable.

這個功能太酷了。 就像在變量中緩存值一樣。

some_variable ||= 10
puts some_variable # => 10some_variable ||= 99
puts some_variable # => 10

You don’t need to use the if statement ever. Just use double pipe equals (||=) and it’s done.

您無需使用if語句。 只需使用雙管道等于(|| =)就可以了。

Simple and easy.

簡單容易。

類靜態方法 (Class static method)

One way I like to write Ruby classes is to define a static method (class method).

我喜歡編寫Ruby類的一種方法是定義一個靜態方法(類方法)。

GetSearchResult.call(params)

Simple. Beautiful. Intuitive.

簡單。 美麗。 直觀。

What happens in the background?

后臺會發生什么?

class GetSearchResultdef self.call(params)new(params).callenddef initialize(params)@params = paramsenddef call# ... your code here ...end
end

The self.call method initializes an instance, and this object calls the call method. Interactor design pattern uses it.

self.call方法初始化一個實例,此對象調用call方法。 交互器設計模式使用它。

吸氣劑和二傳手 (Getters and setters)

For the same GetSearchResult class, if we want to use the params, we can use the @params

對于同一GetSearchResult類,如果要使用參數,則可以使用@params

class GetSearchResultdef self.call(params)new(params).callenddef initialize(params)@params = paramsenddef call# ... your code here ...@params # do something with @paramsend
end

We define a setter and getter:

我們定義一個settergetter:

class GetSearchResultdef self.call(params)new(params).callenddef initialize(params)@params = paramsenddef call# ... your code here ...params # do something with params method hereendprivatedef params@paramsenddef params=(parameters)@params = parametersend
end

Or we can define attr_reader, attr_writer, or attr_accessor

或者我們可以定義attr_readerattr_writerattr_accessor

class GetSearchResultattr_reader :paramdef self.call(params)new(params).callenddef initialize(params)@params = paramsenddef call# ... your code here ...params # do something with params method hereend
end

Nice.

真好

We don’t need to define the getter and setter methods. The code just became simpler, just what we want.

我們不需要定義gettersetter方法。 代碼變得更簡單了,正是我們想要的。

點按 (Tap)

Imagine you want to define a create_user method. This method will instantiate, set the parameters, and save and return the user.

假設您要定義一個create_user方法。 此方法將實例化,設置參數,并保存并返回用戶。

Let’s do it.

我們開始做吧。

def create_user(params)user       = User.newuser.id    = params[:id]user.name  = params[:name]user.email = params[:email]# ...user.saveuser
end

Simple. Nothing wrong here.

簡單。 沒錯

So now let’s implement it with the tap method

現在讓我們用tap方法實現它

def create_user(params)User.new.tap do |user|user.id    = params[:id]user.name  = params[:name]user.email = params[:email]# ...user.saveend
end

You just need to worry about the user parameters, and the tap method will return the user object for you.

您只需要擔心用戶參數, tap方法將為您返回用戶對象。

而已 (That’s it)

We learned I write idiomatic Ruby by coding with

我們了解到我是通過使用

  • array methods

    數組方法
  • syntax

    句法

We also learned how Ruby is beautiful and intuitive, and runs even faster.

我們還了解了Ruby如何美觀,直觀,運行速度更快。

And that’s it, guys! I will be updating and including more details to my blog. The idea is to share great content, and the community helps to improve this post! ?

就是這樣,伙計們! 我將進行更新,并將更多詳細信息添加到我的博客中 。 我們的想法是分享精彩的內容,社區可以幫助改善此信息! ?

I hope you guys appreciate the content and learned how to program beautiful code (and better software).

我希望你們都喜歡這里的內容,并學會了如何編寫漂亮的代碼(以及更好的軟件)。

If you want a complete Ruby course, learn real-world coding skills and build projects, try One Month Ruby Bootcamp. See you there ?

如果您想學習一門完整的Ruby課程,學習實際的編碼技能并構建項目,請嘗試一個月Ruby Bootcamp 。 在那里見you

This post appeared first here on my Renaissance Developer publication.

這個帖子最早出現在這里對我的文藝復興時期的開發者發布

Have fun, keep learning, and always keep coding!

玩得開心,繼續學習,并始終保持編碼!

My Twitter & Github. ?

我的Twitter和Github 。 ?

翻譯自: https://www.freecodecamp.org/news/idiomatic-ruby-writing-beautiful-code-6845c830c664/

慣用過程模型

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395284.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395284.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395284.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

采用晶體管為基本元件的計算機發展階段是,計算機應用基礎知識點

第一章 計算機基礎知識1、計算機發展階段第一代&#xff1a;電子管計算機采用電子管為基本元件&#xff0c;設計使用機器語言或匯編語言。要用于科學和工程計算 第二代&#xff1a;晶體管計算機采用晶體管為基本元件&#xff0c;程序設計采用高級語言&#xff0c;出現了操作系統…

springcloud系列三 搭建服務模塊

搭建服務模塊為了模擬正式開發環境,只是少寫了service層直接在controller里面直接引用,直接上圖和代碼:更為方便: 創建完成之后加入配置: pom.xml文件: <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM…

P1801 黑匣子_NOI導刊2010提高(06)

題目描述 Black Box是一種原始的數據庫。它可以儲存一個整數數組&#xff0c;還有一個特別的變量i。最開始的時候Black Box是空的&#xff0e;而i等于0。這個Black Box要處理一串命令。 命令只有兩種&#xff1a; ADD(x):把x元素放進BlackBox; GET:i加1&#xff0c;然后輸出Bla…

MySql模糊查詢

常規like的使用限制&#xff1a; 1. like %keyword &#xff1a;索引失效&#xff0c;使用全表掃描。但可以通過翻轉函數like前模糊查詢建立翻轉函數索引走翻轉函數索引&#xff0c;不走全表掃描。 2. like keyword% &#xff1a;索引有效。 3. like %keyword% &#xff1a;索引…

python psycopg2使用_python?操作數據庫:psycopg2的使用

1 conn psycopg2.connect(database"testdb", user"postgres",password"cohondob", host"127.0.0.1", port"5432")這個API打開一個連接到PostgreSQL數據庫。如果成功打開數據庫時&#xff0c;它返回一個連接對象。2cursor c…

軟件測試人員棘手的問題,èí?t2aê?μ???ê??êìa£oè?o?±ü?a???′ìá??è±?Y...

¡¡¡¡£££©£¡££¡££££©©£¡¡¡¡¡BUG£££¢¡£££¡££¡£¡£——£…

機器學習實用指南_機器學習方法:實用指南

機器學習實用指南by Karlijn Willems通過Karlijn Willems 機器學習方法&#xff1a;實用指南 (How Machines Learn: A Practical Guide) You may have heard about machine learning from interesting applications like spam filtering, optical character recognition, and …

本地倉庫settings.xml中使用阿里的倉庫

背景 當前使用eclipse自帶的maven碰到兩個蛋疼的問題&#xff1a; maven在國內使用如果不進行FQ則會痛苦不堪如便秘。maven下載大量jar包導致某盤不夠用&#xff0c;需要換大的分區。因此為了解決這個問題就介紹兩個eclipse配置&#xff1a;maven本地路徑配置和maven外部路徑配…

day6_python之md5加密

#md5是不可逆的&#xff0c;就是沒有辦法解密的 Python內置哈希庫對字符串進行MD5加密的方法-hashlibimport hashlib def my_md5(s,salt): #用函數&#xff0c;為了提高代碼的復用率s ssalt #1.必須是字符串news str(s).encode() #2.字符串需要encode編碼后&#xff0…

異步服務_微服務全鏈路異步化實踐

1. 背景隨著公司業務的發展&#xff0c;核心服務流量越來越大&#xff0c;使用到的資源也越來越多。在微服務架構體系中&#xff0c;大部分的業務是基于Java 語言實現的&#xff0c;受限于Java 的線程實現&#xff0c;一個Java 線程映射到一個kernel 線程&#xff0c;造成了高并…

win7打開計算機死機,怎么樣解決Win7系統運行程序引起的死機問題

Win7系統不僅需要使用到電腦中自帶的一些程序&#xff0c;同時&#xff0c;也需要在win7旗艦版電腦中有選擇的自己去安裝一些程序。但是經常有用戶會碰到Win7電腦突然跳出運行程序未響應&#xff0c;出現電腦死機的情況&#xff0c;特別是開的瀏覽器窗口多的時候更是死機的頻繁…

(poj)1064 Cable master 二分+精度

題目鏈接&#xff1a;http://poj.org/problem?id1064 DescriptionInhabitants of the Wonderland have decided to hold a regional programming contest. The Judging Committee has volunteered and has promised to organize the most honest contest ever. It was decided…

PHP中如何解決高并發

PHP中如何解決高并發 1&#xff1a;硬件方面 普通的一個p4的服務器每天最多能支持大約10萬左右的IP&#xff0c;如果訪問量超過10W那么需要專用的服務器才能解決&#xff0c;如果硬件不給力 軟件怎么優化都是于事無補的。主要影響服務器的速度 有&#xff1a;網絡-硬盤讀寫速度…

es6 迭代器_揭秘ES6迭代器和迭代器

es6 迭代器by Tiago Lopes Ferreira由Tiago Lopes Ferreira 揭秘ES6迭代器和迭代器 (Demystifying ES6 Iterables & Iterators) ES6 introduces a new way to interact with JavaScript data structures — iteration. Let’s demystify it.ES6引入了一種與JavaScript數據…

JS之this與語句分號問題v(**V**)v

1 <script >2 //this知識 單詞知識&#xff1a;property&#xff1a;屬性 prototype&#xff1a;原型3 //*Q&#xff1a;什么是this&#xff1f;4 //*A&#xff1a;所有函數內部都有一個this&#xff0c;任何函數本質上都是通過某個對象來調用的&#xff0c;…

計算機聯系函范文,致客戶聯絡函

致客戶聯絡函 相關內容:收到貴支部所發的“函調證明”通知&#xff0c;很高興我校畢業生xxx同學能成為貴支部的黨員發展對象&#xff0c;現對其在我校上學其間的表現證明如下&#xff1a;xxx&#xff0c;女&#xff0c;xxx年7月28日生&#xff0c;團員&#xff0c;XX年8月——X…

c語言堆棧基本代碼入棧出棧_c語言的簡單的進棧出棧

這個代碼運行時只能輸入4個以內的數有輸出4個以上就沒有輸出了求大神看看#include#include#defineStack_Size50typedefstructSeqstack{intelem[Stack_Size];inttop...這個代碼運行時只能輸入4個以內的數有輸出 4個以上就沒有輸出了 求大神看看 #include #include #define Stack…

P1401 城市(30分,正解網絡流)

題目描述 N(2<n<200)個城市&#xff0c;M(1<m<40000)條無向邊&#xff0c;你要找T(1<T<200)條從城市1到城市N的路&#xff0c;使得最長的邊的長度最小&#xff0c;邊不能重復用。 輸入輸出格式 輸入格式&#xff1a; 第1行三個整數N,M,T用空格隔開。 第2行到…

sqlserver游標概念與實例全面解說

引言 我們先不講游標的什么概念&#xff0c;步驟及語法&#xff0c;先來看一個例子&#xff1a; 表一 OriginSalary 表二 AddSalary 現在有2張表&#xff0c;一張是OriginSalary表--工資表&#xff0c;有三個字段0_ID 員工…

為什么Docker對初創企業有意義

by Charly Vega查理維加(Charly Vega) 為什么Docker對初創企業有意義 (Why Docker makes sense for startups) Docker is becoming the standard to develop and run containerized applications.Docker正在成為開發和運行容器化應用程序的標準。 Long ago, this piece of te…