慣用過程模型
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.
這段代碼更具表現力,我希望方法的答案返回true或false值。
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:
我們定義一個setter和getter:
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_reader , attr_writer或attr_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.
我們不需要定義getter和setter方法。 代碼變得更簡單了,正是我們想要的。
點按 (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/
慣用過程模型