博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
惯用过程模型_惯用的Ruby:编写漂亮的代码
阅读量:2528 次
发布时间:2019-05-11

本文共 10945 字,大约阅读时间需要 36 分钟。

惯用过程模型

Ruby is a beautiful programming language.

Ruby是一种美丽的编程语言。

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

根据的官方网页,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 , a Japanese software engineer. Since 2011, he has been the chief designer & software engineer for Ruby at .

Ruby由日本软件工程师创建。 自2011年以来,他一直担任 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?  trueendputs "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 ||= 10puts some_variable # => 10some_variable ||= 99puts 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 GetSearchResult  def self.call(params)    new(params).call  end  def initialize(params)    @params = params  end  def call    # ... your code here ...  endend

The self.call method initializes an instance, and this object calls the call method. 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 GetSearchResult  def self.call(params)    new(params).call  end  def initialize(params)    @params = params  end  def call    # ... your code here ...    @params # do something with @params  endend

We define a setter and getter:

我们定义一个settergetter:

class GetSearchResult  def self.call(params)    new(params).call  end  def initialize(params)    @params = params  end  def call    # ... your code here ...    params # do something with params method here  end  private  def params    @params  end  def params=(parameters)    @params = parameters  endend

Or we can define attr_reader, attr_writer, or attr_accessor

或者我们可以定义attr_readerattr_writerattr_accessor

class GetSearchResult  attr_reader :param  def self.call(params)    new(params).call  end  def initialize(params)    @params = params  end  def call    # ... your code here ...    params # do something with params method here  endend

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.new  user.id    = params[:id]  user.name  = params[:name]  user.email = params[:email]  # ...  user.save  userend

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.save  endend

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 . 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 . See you there ☺

如果您想学习一门完整的Ruby课程,学习实际的编码技能并构建项目,请尝试 。 在那里见you

This post appeared first on my .

这个帖子最早出现对我的 。

Have fun, keep learning, and always keep coding!

玩得开心,继续学习,并始终保持编码!

My & . ☺

我的和 。 ☺

翻译自:

惯用过程模型

转载地址:http://vtrwd.baihongyu.com/

你可能感兴趣的文章
Android Socket连接PC出错问题及解决
查看>>
Android Studio-—使用OpenCV的配置方法和demo以及开发过程中遇到的问题解决
查看>>
第2天线性表链式存储
查看>>
python自动化测试-D11-学习笔记之一(yaml文件,ddt)
查看>>
mysql存储过程使用游标循环插入数据
查看>>
Ubuntu 12.04 添加新用户并启用root登录
查看>>
20145309信息安全系统设计基础第9周学习总结上
查看>>
c# 字段、属性get set
查看>>
td内容超出隐藏
查看>>
Spring CommonsMultipartResolver 上传文件
查看>>
Settings app简单学习记录
查看>>
SQLAlchemy
查看>>
多线程
查看>>
使用缓存的9大误区(下)转载
查看>>
appium键值对的应用
查看>>
MyEclipse 8.X 通用算法
查看>>
selenium.Phantomjs设置浏览器请求头
查看>>
分布式数据库如何选择,几种分布式数据库优缺点一览
查看>>
BZOJ 4443: 小凸玩矩阵【二分图】
查看>>
苹果 OS X制作u盘启动盘
查看>>