ruby中argv_Ruby中的速成课程

ruby中argv

In the last five years or so, Ruby has gained up in popularity and a lot of software professionals have switched to or added it to their technical skills.

在过去的五年左右的时间里,Ruby逐渐流行起来,并且许多软件专业人士已将Ruby转换或添加到他们的技术技能中。

Though the language is still in the process of improvement and optimization, there is no denying that it is catching up with giants like PHP and Python.

尽管该语言仍处于改进和优化过程中,但不可否认的是它正在赶上PHP和Python之类的巨头。

Moreover, the language has helped realize some of the dream projects of the last decade such as Github and Twitter.

此外,该语言还帮助实现了过去十年中的一些梦想项目,例如GithubTwitter

So, don't you think it is about time you learned it?

所以,您不认为这是您学习的时候了吗?

In this tutorial, you will learn about:

在本教程中,您将了解:

  1. Installing Ruby.

    安装Ruby。
  2. Architectural foundations of the language.

    语言的建筑基础。
  3. Operators.

    运营商。
  4. Data types.

    数据类型。
  5. Conditional statements.

    条件语句。
  6. Looping code.

    循环代码。
  7. Object-oriented programming.

    面向对象的编程。
  8. Globals and constants.

    全局和常量。
  9. Loading external files/code.

    加载外部文件/代码。
  10. Ruby Gems.

    Ruby宝石。

In order to follow along swiftly, an intermediate level of expertise in any programming language is highly recommended.

为了快速跟进,强烈建议您精通任何编程语言的中级专业知识。

If you are a programming beginner looking to learn Ruby, this tutorial is not for you.

如果您是想学习Ruby的编程新手,那么本教程不适合您。

This will be a very fast paced, practical hands-on of the Ruby language with lots to absorb. Move section by section and go at your own pace. I highly recommend you to play around with a single concept before moving on to the next one.

这将是一个非常快的节奏,非常实用的Ruby语言动手实践,需要学习很多东西。 逐节移动并按照自己的步调前进。 我强烈建议您在进入下一个概念之前先尝试一个概念。

安装Ruby ( Installing Ruby )

You can install Ruby using an executable installer (for Windows) or a package manager (for *nix and OSX).

您可以使用可执行安装程序(对于Windows)或程序包管理器(对于* nix和OSX)安装Ruby。

The official installation guide provides a detailed account of the various methods available.

官方安装指南详细介绍了可用的各种方法。

For this tutorial, I will show you how to install Ruby using a third party tool, Ruby Version Manager (RVM).

在本教程中,我将向您展示如何使用第三方工具Ruby Version Manager(RVM)来安装Ruby。

For beginners, managing Ruby versions may not be a big deal but as you develop more and more in Ruby, you will come to realize what a blessing RVM is.

对于初学者来说,管理Ruby版本可能不是什么大问题,但是随着您在Ruby中开发越来越多,您将逐渐意识到RVM是多么幸运。

Execute the following command to install the RVM author's public key.

执行以下命令以安装RVM作者的公钥。

$ gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

Next, install RVM.

接下来,安装RVM。

$ \curl -sSL https://get.rvm.io| bash -s stable

You will be prompted through the installation steps.

系统将提示您完成安装步骤。

Once done, restart your terminal session and execute the following command to verify correct installation of RVM.

完成后,重新启动终端会话并执行以下命令以验证RVM的正确安装。

$ rvm --help

If you see RVM's comprehensive help page, congratulations!

如果您看到RVM的综合帮助页面,那么恭喜!

Finally, we need to tell RVM which version of Ruby to install.

最后,我们需要告诉RVM要安装哪个版本的Ruby。

$ rvm --defaultinstall 2.3.1

We have specified the Ruby version 2.3.1 to be installed and also passed in the --default flag to set this as our default Ruby version.

我们已指定要安装的Ruby版本2.3.1 ,并且还传递了--default标志以将其设置为我们的默认Ruby版本。

RVM will prompt you with the installation steps as Ruby is installed.

RVM将在安装Ruby时提示您安装步骤。

Once finished, you can execute the following command to verify correct installation of Ruby.

完成后,您可以执行以下命令来验证Ruby的正确安装。

$ ruby -v

If you see the Ruby version you specified to be installed, I have got good news for you!

如果您看到指定要安装的Ruby版本,那么我对您来说是个好消息!

执行Ruby代码 ( Executing Ruby Code )

You are free to try, hack, improvise, and build upon the code that will be presented during the course of this tutorial.

您可以随意尝试,修改,临时创建本教程中将要介绍的代码。

Simply place your code inside a file with a .rb extension.

只需将代码放在扩展名为.rb的文件中。

Next, use your terminal to invoke Ruby and specify the code file to execute.

接下来,使用终端调用Ruby并指定要执行的代码文件。

$ ruby<path-to-your-.rb-file>
# example: ruby /Volumes/Work/Ruby/my_code.rb

Your Ruby code will be executed and the output will be produced at the terminal.

您的Ruby代码将被执行,输出将在终端上产生。

If you want things to move a little quicker, you can try the interactive Ruby shell(IRB).

如果您希望事情快一点,可以尝试交互式Ruby Shell(IRB)。

IRB is a program that is bundled with your Ruby installation and helps you test Ruby code by accepting Ruby statements and producing their output on the screen.

IRB是与Ruby安装捆绑在一起的程序,可以通过接受Ruby语句并在屏幕上生成它们的输出来帮助您测试Ruby代码。

You can invoke IRB by simply executing the command irb after you have installed Ruby.

您可以在安装Ruby之后通过简单地执行irb命令来调用IRB。

The IRB prompt will immediately show up on at the terminal, ready to accept Ruby commands.

IRB提示将立即显示在终端上,准备接受Ruby命令。

建筑基础 ( Architectural Foundations )

Ruby was created around the mid 1990s by Yukihiro "Matz" Matsumoto as a purely object oriented programming language, inspired by Perl, Smalltalk, Eiffel, Ada, and Lisp.

Ruby是在1990年代中期由Yukihiro“ Matz” Matsumoto创立的,它是一种纯粹的面向对象的编程语言,受Perl,Smalltalk,Eiffel,Ada和Lisp的启发。

Ruby was created to make programming fun. At times, Ruby code is so beautifully written that it reads almost like English.

Ruby的创建使编程变得有趣。 有时,Ruby代码编写得如此精美,以至于其读起来几乎像英语。

The best thing about Ruby is despite it's complexities, it's a joy to work with.

关于Ruby的最好之处是尽管它很复杂,但使用它还是一种乐趣。

Everything you deal with in Ruby is actually an object, even though from a syntactical point of view, it may not appear to be.

在Ruby中处理的所有内容实际上都是对象,即使从语法角度来看,它似乎也不是。

Consider the following code snippet.

考虑以下代码片段。

puts"This is a simple code snippet"
puts self.class

We have just echoed a very simple string and printed the class of the self(which points to the current context) object.

我们刚刚回显了一个非常简单的字符串,并打印了self(指向当前上下文)对象的类。

It produces the output.

它产生输出。

This is a simple code snippet
Object

As we have come to know it, should not the self keyword work only inside a class? Why was our reality not shattered with an unpleasant not defined error?

众所周知,self关键字不应该仅在类内部起作用吗? 为什么我们的现实没有因令人not defined愉快的not defined错误而崩溃?

It is because every type in Ruby inherits from the base object Object and even if our code does not define a class, it is compiled as part of and extends upon the object Object.

这是因为Ruby中的每种类型都继承自基础对象Object ,即使我们的代码未定义类,它也会作为对象Object一部分进行编译并扩展。

The fact that everything is an object and should be treated like so puts an enormous burden on you as a programmer where you have to make sure your code is purely object oriented.

一切都是对象,应该这样对待的事实为程序员带来了巨大负担,在程序员中,您必须确保代码纯粹是面向对象的。

Luckily, to keep things neat, easy to read, and understand, Ruby has a lot of, what we call, syntactic sugar.

幸运的是,为了使事情保持整洁,易于阅读和理解,Ruby提供了很多所谓的语法糖。

puts2 + 2
puts 2.+(2)

The first line of code adds two integers. The second line does the same but it actually calls the addition method on the integer object, passing in another integer.

代码的第一行将两个整数相加。 第二行执行相同的操作,但实际上它在整数对象上调用加法,并传入另一个整数。

Both the lines of code produce the same output.

这两行代码产生相同的输出。

4
4

Obviously, the first line of code is more natural and easier to read. The second just re-iterates the point that everything in Ruby is an object.

显然,第一行代码更自然,更易于阅读。 第二篇再次重申了Ruby中的所有内容都是对象的观点。

I highly recommend you to read the official Ruby about page, some pretty fascinating bits of knowledge in there.

我强烈建议您阅读官方的Ruby about页面 ,那里有一些非常有趣的知识。

入门入门 ( A Short Primer )

Before we start, let us take care of the small things that will help you better understand the sections and code that follows.

在开始之前,让我们先处理一些小事情,这些小事情将帮助您更好地理解后面的部分和代码。

Single-line code comments start with the hash # sign whereas multi-line comments are enclosed within =begin and =end blocks.

单行代码注释以井号#开头,而多行注释则包含在=begin=end块内。

Further, the =begin and =end constructs should be right at the start of the line for multi-line comments to work. Single-line code comments can be added anywhere using the # construct.

此外, =begin=end构造应该在行的开头,这样多行注释才能起作用。 可以使用#结构在任何地方添加单行代码注释。

Here are a few examples.

这里有一些例子。

# This is a single line comment
test = true

income = 0 # set income to zero

# Correct multi-line comment
=begin
# lots of code
=end

# Incorrect multi-line comment
    =begin
# lots of code
    =end

Code blocks can be enclosed withing curly braces {} or do and end keywords.

代码块可以用大括号{}doend关键字括起来。

while true do
  # some code
end

while true {
  # some code
}

At times, you have to yield or pass in variables to blocks or loops. You can do that using ||.

有时,您必须让变量屈服或将变量传递给块或循环。 您可以使用||

10.times do |num|
  puts num
end

[1, 2 ,3, 4, 5].each do |num|
  puts num
end  

Code lines are terminated using the new-line character so one you are done writing a line of code, simply hit enter. There is no need to terminate a line with ; or any other character.

代码行使用换行符终止,因此您只要编写一行代码,只需按Enter键即可。 无需使用终止行; 或其他任何字符。

经营者 ( Operators )

Let us start with the various operators available in Ruby.

让我们从Ruby中可用的各种运算符开始。

The following table provides a comprehensive list of the Ruby operators, in order of their precedence.

下表按优先级提供了Ruby运算符的完整列表。

Operator NameMethod NameArity(numbers of operands)
Boolean not!1
Bitwise complement~1
Unary plus+1
Exponentiation**2
Unary minus-1
Multiplication*2
Division/2
Modulo%2
Addition+2
Subtraction-2
Bitwise shift-left<<2
Bitwise shift-right>>2
Bitwise and&2
Bitwise or|2
Bitwise xor^2
Less than<2
Less than or equal to<=2
Greater than or equal to>=2
Greater than>2
Equality==2
Equality===2
Equality!=2
Pattern matching=~2
Pattern matching!~2
Comparision<=>2
Boolean and&&2
Boolean or||2
Assignment=, **=, *=, /=, %=, +=, -=, <<=, >>=, &&=, &=, ||=, |=, ^=2
Boolean notnot1
Boolean andand2
Boolean oror2
运营商名称 方法名称 Arity(操作数)
布尔非 1个
按位补码 1个
一元加 + 1个
求幂 ** 2
一元减 -- 1个
乘法 * 2
/ 2
模数 2
加成 + 2
减法 -- 2
左移 << 2
按位右移 >> 2
按位和 2
按位或 | 2
按位异或 ^ 2
少于 < 2
小于或等于 <= 2
大于或等于 > = 2
比...更棒 > 2
平等 == 2
平等 === 2
平等 != 2
模式匹配 =〜 2
模式匹配 !〜 2
比较 <=> 2
布尔和 && 2
布尔值或 || 2
分配 =,** =,* =,/ =,%=,+ =,-=,<< =,>> =,&& =,&=,|| =,| =,^ = 2
布尔非 1个
布尔和 2
布尔值或 要么 2

You have used most of these operators in various programming languages over the years so it must be pretty clear how they are used.

这些年来,您已经在各种编程语言中使用了大多数这些运算符,因此必须非常清楚如何使用它们。

Still, to iron things out, let us see them in action.

尽管如此,还是要解决这些问题,让我们看看它们的作用。

# Boolean not
puts (!false) # prints true
puts (!true)  # prints false

# Bitwise complement
puts "#{5783.to_s(2)} = #{(~5783).to_s(2)}" # prints 1011010010111 = -1011010011000  

# Unary plus
puts (+2) # prints 2

# Exponentiation
puts (8**2) # prints 64(8x8)

# Unary minus
puts (-2) # prints -2

# Multiplication
puts (2*2) # prints 4

# Division
puts (90/3) # prints 30

# Modulo
puts (9 % 2) # prints 1

# Addition
puts (2+2) # prints 4

# Subtraction
puts (100 - 100) # prints 0

# Bitwise shift-left
puts "#{5783.to_s(2)} = #{(5783 << 3).to_s(2)}"  # prints 1011010010111 = 1011010010111000 

# Bitwise shift-right
puts "#{5783.to_s(2)} = #{(5783 >> 3).to_s(2)}"  # prints 1011010010111 = 1011010010

# Bitwise and
puts (true & false) # prints false

# Bitwise or
puts (true | false) # prints true

# Bitwise xor
puts (false ^ false) # prints false

# Less than
puts (2 < 4) # prints true

# Less than or equal to
puts (4 <= 4) # prints true

# Greater than or equal to
puts (6 >= 2) # prints true

# Greater than
puts (6 > 10) # prints false

# Equality
puts (2 == 2 ) # prints true

# Equality
puts (2 === 2) # prints true

# Inequality
puts (2 != 5) # prints true

# Pattern matching
puts (/test/ =~ "abcdefghijtestklmnoqrstuvwxyz") # prints 10
puts (/test/ =~ "abcdefghijklmnoqrstuvwxyz") # prints nil

# Pattern matching
puts (/test/ !~ "abcdefghijtestklmnoqrstuvwxyz") # prints false
puts (/test/ !~ "abcdefghijklmnoqrstuvwxyz") # prints true

# Comparision
puts (5 <=> 10) # prints -1 
puts (10 <=> 5) # prints 1 
puts (5 <=> 5) # prints 0 

# Boolean and
puts (true && false) # prints false

# Boolean or
puts (true || false) # prints true

# Assignment
num = 10
num **= 10
puts num # prints 10000000000

# Boolean not
puts (not false) # prints true

# Boolean and
puts (true and false) # print false

# Boolean or
puts (true or false) # prints true

An interesting thing to know about operators, as you have seen in the previous section, is they are simply methods on an object.

正如您在上一节中所看到的,有关操作符的一件有趣的事情是,它们只是对象上的方法。

Expanding on that concept, here is the equivalent code for operators (wherever available), calling them as object methods.

在这个概念上进行扩展,这里是运算符的等效代码(如果有),将其称为对象方法。

# Boolean not
puts (false.!) # prints true
puts (true.!)  # prints false

# Bitwise complement
puts "#{5783.to_s(2)} = #{5783.~.to_s(2)}" # prints 1011010010111 = -1011010011000 

# Unary plus
puts (+2) # prints 2

# Exponentiation
puts (8.**(2)) # prints 64(8x8)

# Unary minus
puts (-2) # prints -2

# Multiplication
puts (2.*(2)) # prints 4

# Division
puts (90./(3)) # prints 30

# Modulo
puts (9.%(2)) # prints 1

# Addition
puts (2.+(2)) # prints 4

# Subtraction
puts (100.-(100)) # prints 0

# Bitwise shift-left
puts "#{5783.to_s(2)} = #{5783.<<(3).to_s(2)}" # prints 1011010010111 = 1011010010111000 

# Bitwise shift-right
puts "#{5783.to_s(2)} = #{5783.>>(3).to_s(2)}" # prints 1011010010111 = 1011010010

# Bitwise and
puts (true.&(false)) # prints false

# Bitwise or
puts (true.|(false)) # prints true

# Bitwise xor
puts (false.^(false)) # prints false

# Less than
puts (2.<(4)) # prints true

# Less than or equal to
puts (4.<=(4)) # prints true

# Greater than or equal to
puts (6.>=(2)) # prints true

# Greater than
puts (6.>(10)) # prints false

# Equality
puts (2.==(2)) # prints true

# Equality
puts (2.===(2)) # prints true

# Inequality
puts (2.!=(5)) # prints true

# Pattern matching
puts ("abcdefghijtestklmnoqrstuvwxyz".=~(/test/)) # prints 10
puts ("abcdefghijklmnoqrstuvwxyz".=~(/test/)) # prints nil

# Pattern matching
puts ("abcdefghijtestklmnoqrstuvwxyz".!~(/test/)) # prints false
puts ("abcdefghijklmnoqrstuvwxyz".!~(/test/)) # prints true

# Comparision
puts (5.<=>(10)) # prints -1 
puts (10.<=>(5)) # prints 1 
puts (5.<=>(5)) # prints 0 

# Boolean and
puts (true && false) # prints false

# Boolean or
puts (true || false) # prints true

# Assignment
num = 10
num **= 10
puts num # prints 10000000000

# Boolean not
puts (not false) # prints true

# Boolean and
puts (true and false) # print false

# Boolean or
puts (true or false) # prints true

Operator methods also serve as reserved keyword method names for when you wish to define an operator based method on your objects.

当您希望在对象上定义基于运算符的方法时,运算符方法也可用作保留的关键字方法名称。

For example, say we have an employee class and we wish to define an addition method on it.

例如,假设我们有一个雇员类,并且希望在其上定义一个加法。

For our case, let us say we wish to have an addition method on the employee class based on their salaries.

对于我们的情况,让我们说我们希望基于雇员的薪水在雇员类别上增加一种方法。

class Employee

  def +(employee)
    @salary + employee.salary
  end

end

核心数据类型 ( Core Data Types )

The core data types in Ruby are -numbers -strings -symbols -arrays -hashes -and booleans.

Ruby中的核心数据类型是-numbers -strings -symbols -arrays -hashhes-和booleans。

Since it is imperative that you learn to use the correct data type for each use case, let us look at each of them in a bit of detail.

由于必须学会为每种用例使用正确的数据类型,因此让我们对它们进行详细介绍。

号码 (Numbers)

Numbers are simply numbers. A number can be an integer like 123 or a decimal like 12.34.

数字就是数字。 数字可以是123这样的整数,也可以是12.34这样的十进制。

Moreover, numbers can be positive or negative with a leading minus(-) sign.

此外,数字可以带正负号(-)的正或负。

num1= 12345
puts num1 # prints 12345

num2 = 123.45
puts num2 # prints 123.45

num3 = -12345
puts num3 # prints -12345

num4 = -123.45
puts num4 # prints -123.45

When declaring numbers, you can use a _ to separate them by thousands for better readability and Ruby will just ignore the underscore. For example, 1_000_000 can be used to declare the number 1000000.

声明数字时,可以使用_将它们分隔成数千个,以提高可读性,而Ruby只会忽略下划线。 例如, 1_000_000可用于声明数字1000000

num1= 1_000_000
puts num1 # prints 1000000

Behind the scenes, different object types are used to account for different types of numbers.

在幕后,使用不同的对象类型来说明不同类型的数字。

For example, the Fixnum class is used for integers but for very large integers, the Bignum class is used. Similarly, Float and BigDecimal classes are used for small and very large decimal numbers respectively.

例如, Fixnum类用于整数,但对于很大的整数,则使用Bignum类。 同样, FloatBigDecimal类分别用于较小和非常大的十进制数。

The last thing to remember about numbers is, unless there is a decimal involved, the output of a calculation will always be integer, even if mathematically, the calculation results in a decimal based answer.

关于数字,最后要记住的是,除非涉及到小数,否则计算的输出将始终是整数,即使在数学上,该计算也会得出基于小数的答案。

num1= 123/2
puts num1 # prints 61

num2 = 123/2.0
puts num2 # prints 61.5

弦乐 (Strings)

Strings are a bunch of characters knit together. Apart from using single ' and double " quotes, there are a number of ways you can declare strings.

字符串是一串编织在一起的字符。 除了使用单一的'"行情,也有许多可以声明字符串的方式。

str1= 'This is a string'
puts str1 # prints This is a string

str2 = "This is a string"
puts str2 # prints This is a string

str3 = %Q(This is a string)
puts str3 # prints This is a string

str4 = %q(This is a string)
puts str4 # prints This is a string

str5 = String.new("This is a string")
puts str5 # prints This is a string

%Q and %q are the equivalent of double quote and single quote delimiters. You can also define your custom delimiter by prepending it with a %.

%Q%q等效于双引号和单引号定界符。 您还可以通过在其前面加上%来定义自定义定界符。

str1= %(This is a string)
puts str1 # prints This is a string

str2 = %{This is a string}
puts str2 # prints This is a string

str3 = %[This is a string]
puts str3 # prints This is a string

str4 = %-This is a string-
puts str4 # prints This is a string

You can declare multi-line strings using here docs. Here docs are simply string delimiters that are prepended with <<. Here docs give you the freedom to spread your strings over multiple lines.

您可以在此处docs声明多行字符串。 这里的文档只是字符串分隔符,并以<<开头。 在这里,文档使您可以自由地将字符串分布在多行上。

str1= <<GROCERIES
1. Milk
2. Sugar
3. Banana
4. Orange
5. Strawberries
GROCERIES
puts str1 # prints 1. Milk\n2. Sugar\n3. Banana\n4. Orange\n5. Strawberries\n

A very important concept regarding strings is interpolation. Using the symbol #{}, you can call in dynamic data and variables in your strings.

关于字符串的一个非常重要的概念是插值。 使用符号#{} ,您可以在字符串中调用动态数据和变量。

str1= "2 + 10 is #{2+10}"
puts str1 # prints 2 + 10 is 12

Notice how the content between #{ and } was treated as numbers and the actual value of the calculation was substituted in the string.

注意如何将#{}之间的内容视为数字,并将计算的实际值替换为字符串。

符号 (Symbols)

Symbols are declared by prepending a colon : to them. If your symbol contains spaces, you have to enclose it within single ' or double " quotes after prepending it with a colon :.

符号前面加上一个冒号宣布:他们。 如果你的符号包含空格,你有一个内括起来'或双"用冒号前面加上引号后:

If you are just starting out with Ruby, symbols can be a funny concept to grasp.

如果您刚开始使用Ruby,则符号可能是一个很有趣的概念。

For a start, you can think of symbols as tokenized strings. The major difference between strings and symbols is if declared multiple times, no two strings point to the same object. However, in case of symbols, no matter where and how many times you declare them in your programs, a single symbol will always point to the same object.

首先,您可以将符号视为标记化字符串。 字符串和符号之间的主要区别在于,如果多次声明,则不会有两个字符串指向同一对象。 但是,在使用符号的情况下,无论您在程序中在何处声明它们多少次,单个符号始终将指向同一对象。

The following code is a proof of that concept.

以下代码证明了这一概念。

str1= "I am a string"

str2 = "I am a string"

str3 = "I am a string"

puts str1.object_id # prints 70229514771560

puts str2.object_id # prints 70229518541680

puts str3.object_id # prints 70229518606820

str1 = :"I am a string"

str2 = :"I am a string"

str3 = :"I am a string"

puts str1.object_id # prints 1151348

puts str2.object_id # prints 1151348

puts str3.object_id # prints 1151348

Notice how in the case of a symbol, the str1, str2, and str3 objects have the same object_id which proves they point to the same object.

请注意,在使用符号的情况下, str1str2str3对象如何具有相同的object_id ,从而证明它们指向同一对象。

Symbols are highly memory efficient as compared to strings and are used in cases where identical strings are required such as hash keys.

与字符串相比,符号具有更高的存储效率,并且在需要相同字符串(例如哈希键)的情况下使用。

The object_id is a unique id that Ruby uses internally to keep track of all the objects in your program.

object_id是Ruby内部用于跟踪程序中所有对象的唯一ID。

数组 (Arrays)

An array is simply a collection of objects. You can add any type and number of objects into an array and retrieve them using a zero-based index.

数组只是对象的集合。 您可以将任何类型和数量的对象添加到数组中,并使用基于零的索引来检索它们。

Arrays can be declared using multiple ways.

可以使用多种方式声明数组。

arr1= ["I", "am", "an", "array"] # results in ["I", "am", "an", "array"]

arr2 = %W(I am an array) # results in ["I", "am", "an", "array"]

arr3 = %w(I am an array) # results in ["I", "am", "an", "array"]

puts arr1[0] # prints I

puts arr1[1] # prints am

puts arr1[2] # puts an

puts arr1[3] # prints array

The push and pop methods available on an array object can enable you to use an array as a stack.

数组对象上可用的pushpop方法可使您将数组用作堆栈。

arr= []

arr.push(1) # results in [1]
arr.push(2) # results in [1, 2]
arr.push(3) # results in [1, 2, 3]

arr.pop # returns 3 / arr = [1, 2]
arr.pop # returns 2 / arr = [1]
arr.pop # returns 1 / arr = []

散列 (Hashes)

You can think of hashes as special arrays where you not only have the freedom to declare the values, but also the keys associated with those values.

您可以将哈希视为特殊的数组,您不仅可以自由声明值,还可以自由声明与这些值关联的键。

The values in a hash can be any object. The keys are usually a string or a symbol.

哈希中的值可以是任何对象。 键通常是字符串或符号。

From our earlier discussion, since symbols are memory efficient, it is advised that you use symbols as keys in your hash.

从我们前面的讨论中,由于符号是高效存储的,因此建议您将符号用作哈希中的键。

Another important thing to know about hashes is up until Ruby's version 1.9.3, hashes were declared using =>, which is known as the hash rocket syntax.

关于哈希的另一件重要的事情是直到Ruby的1.9.3版才使用=>声明了哈希,这被称为哈希火箭语法。

hsh1= { "one" => 1, "two" => 2, "three" => 3 } # results in {"one"=>1, "two"=>2, "three"=>3}

hsh2 = { :one => 1, :two => 2, :three => 3 } # results in {:one=>1, :two=>2, :three=>3}

The hash rocket syntax works for both symbol and string keys.

哈希火箭语法适用于符号键和字符串键。

For versions greater than 1.9.3, a shorthand syntax is available for when you use symbols as hash keys.

对于大于1.9.3版本,当您使用符号作为哈希键时,可以使用简写语法。

hsh= { one: 1, two: 2, three: 3 } # results in {:one=>1, :two=>2, :three=>3}

正确,错误和无 (True, False, and Nil)

The true and false objects represent booleans and are used to check for truth values.

truefalse对象代表布尔值,用于检查真值。

In Ruby, you also have a nil object which symbolizes the absence of something. It is used for cases where you wish to check if something exists, not that it is true or false.

在Ruby中,您还有一个nil对象,它表示没有东西。 它用于需要检查是否存在某些东西的情况,而不是检查是对还是错。

The true, false, and nil classes are also represented by the capitalized versions, TRUE, FALSE, and NIL.

true,false和nil类也由大写版本TRUEFALSENIL

有条件的 ( Conditionals )

You would hardly ever write a computer program that does not make decisions or alters its path of execution based on certain conditions.

您几乎不会编写不会根据某些条件做出决定或更改其执行路径的计算机程序。

Through examples, let us look at the conditional constructs Ruby provides.

通过示例,让我们看一下Ruby提供的条件构造。

income= 1200
expense = 1000

if expense > income
  puts "You need to reduce your expenses"
end

The ever famous if conditional is used to take action if a certain condition is true.

如果某个条件为真,则使用著名的if条件来执行操作。

The if conditional can be further extended to check for other cases using elsif and else.

可以进一步扩展if条件,以使用elsifelse检查其他情况。

income= 1200
expense = 1000

if expense > income
  puts "You need to reduce your expenses."
elsif income > expense
  puts "You are doing great!"
elsif income == expense
  puts "I also like to live dangerously :)"
else
  puts "How did I get here?"  
end

The elsif conditional allows us to check for the other two possible scenarios in case of income and expense variables. The final else allows us to execute a statement if none of the conditional statement before it turn out to be true.

elsif条件允许我们在incomeexpense变量的情况下检查其他两种可能的情况。 如果条件查询中没有一个是事实,那么最后的else允许我们执行一条语句。

The opposite of if, the unless conditional is also available.

与if相反, unless有条件。

income= 1200
expense = 1000

unless income > expense
  puts "You need to reduce your expenses."
end

The unless conditional fires for all cases where your provided expression turns out to be false.

对于您提供的表达式结果为false的所有情况,除非条件触发。

The unless conditional can also be extended using the else conditional.

除非条件,也可以使用else条件扩展。

income= 1200
expense = 1000

unless income > expense
  puts "You need to reduce your expenses."
else
  puts "You are doing great!"
end

The else that is paired with an unless would fire when the expression you have provided turns out to be true.

当您提供的表达式为true时,与no配对的else将触发。

In Ruby, the if and unless conditionals are often mixed with the assignment operator, resulting in a conditional assignment.

在Ruby中,if和if条件经常与赋值运算符混合,从而产生条件赋值。

income= 1000
expense = 1500

progress = "positive" if income > expense

progress = "negative" unless income > expense

Lastly, you have the case statement that can be used to check a single variable for a range of values.

最后,您具有case语句,可用于检查单个变量的值范围。

age= 18

case age
  when 18
    puts "You need to grow up!"
  else
    puts "Enjoying adulthood?"
end

You can also specify a comma-separated list of values to check against a single case.

您还可以指定一个用逗号分隔的值列表,以检查单个大小写。

age= 18

case age
  when 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
    puts "You need to grow up!"
  else
    puts "Enjoying adulthood?"
end

迭代器 ( Iterators )

Imagine a world where any instruction that needed to be executed a number of times, had to be explicitly repeated in a computer program. What kind of a world would that be?

想象一下一个世界,其中任何需要多次执行的指令都必须在计算机程序中明确重复。 那将是一个什么样的世界?

Savage!

野蛮人!

Fortunately, iterators spare us the savagery.

幸运的是,迭代器使我们免于繁琐。

Let us look at the different ways to loop code.

让我们看看循环代码的不同方法。

(While)

The while loop is used to continuously execute a piece of code until a certain condition evaluates to false.

while循环用于连续执行一段代码,直到某个条件的值为假。

There are two variations of the while loop available. One where you specify the condition before the code to loop, and one where the condition comes after.

while循环有两种变体。 一种是在要循环的代码之前指定条件,另一种是在条件之后的条件。

num= 0

while num < 5 do 
  puts num
  num += 1
end

# prints 0\n 1\n 2\n 3\n 4\n

num = 0

begin
  puts num
  num += 1    
end while num < 5

# prints 0\n 1\n 2\n 3\n 4\n

Generally, inside the while loop, you would have some sort of code that would eventually cause the condition to evaluate to false, hence breaking out of the loop.

通常,在while循环内部,您将拥有某种代码,这些代码最终将导致条件的计算结果为false,从而中断了循环。

A while loop is also used to keep taking a certain action during the course of a program such as prompting the user for input.

while循环还用于在程序执行过程中继续执行某些操作,例如提示用户输入。

while true do
  num = gets
  puts num
end

直到 (Until)

An until loop works the exact same way as the while loop. The only difference is an until loop continues to execute as long as the condition evaluates to false.

until循环与while循环完全相同。 唯一的区别是,只要条件评估为false,就会一直执行直到循环。

Just like the while loop, there are also two variations of the until loop available. One where you specify the condition before the code to loop, and one where the condition comes after.

就像while循环一样,直到循环还有两个变体。 一种是在要循环的代码之前指定条件,另一种是在条件之后的条件。

num= 0

until num > 5 do 
  puts num
  num += 1
end

# prints 0\n 1\n 2\n 3\n 4\n 5\n

num = 0

begin
  puts num
  num += 1    
end until num > 5

# prints 0\n 1\n 2\n 3\n 4\n 5\n

对于/每个 (For/Each)

The for and each loops are used in conjunction with arrays and ranges to execute a piece of code a certain number of times.

foreach循环与数组和范围结合使用以执行一段代码一定次数。

Before we move forward, let us have a quick word on ranges.

在继续前进之前,让我们先简单介绍一下范围。

In Ruby, ranges are simply a way to declare a sequence of consecutive values.

在Ruby中,范围只是声明连续值序列的一种方式。

They are declared using the .. and ... operators.

它们使用.....运算符声明。

Ranges are inclusive of the starting and ending members in case of the ..operator whereas in case of ..., the ending member is excluded.

..运算符的情况下,范围包括开始和结束成员,而在...情况下,不包括结束成员。

rng= 1..100 # rng is integers from 1 to 100

rng = 1...100 # rng is integers from 1 to 99

rng = a..z # rng is alphabets from a to z

rng = a...z # rng is alphabets from a to y

Coming back to for and each loops, here is how to go about them.

返回for和每个循环,这里是如何进行循环。

arr= [0, 1, 2, 3, 4, 5]

for i in arr do
  puts i
end

# prints 0\n 1\n 2\n 3\n 4\n 5\n

arr.each do | i |
  puts i
end

# prints 0\n 1\n 2\n 3\n 4\n 5\n

rng = 0..5

for i in rng do
  puts i
end

# prints 0\n 1\n 2\n 3\n 4\n 5\n

rng.each do | i |
  puts i
end

# prints 0\n 1\n 2\n 3\n 4\n 5\n

下一个/中断 (Next/Break)

The next and break keywords don't quite allow you to loop a piece of code but since they are used to skip on and break out of iterations respectively, it's worth mentioning them with loops.

nextbreak关键字并不完全允许您循环一段代码,但是由于它们分别用于跳过和中断迭代,因此值得在循环中提及它们。

The following code sample demonstrates their usage.

下面的代码示例演示了它们的用法。

rng= 1..100

rng.each do | i |
  if i == 51
    break
  end  
  if i % 2 == 0
    puts i
  else
    next
  end
end

Our rng is declared from one to hundred. All even numbers from one to hundred should be printed. Since we break out of the loop when i becomes fifty one, only even numbers from one to fifty are printed. In case a number is not even, we simply move to the next iteration using next.

我们的rng从一到一百被宣布。 应当打印从100到100的所有偶数。 由于当i变成五十一时我们跳出循环,因此仅打印从一到五十的偶数。 如果数字不是偶数,我们只需使用next移至下一个迭代。

方法/功能 ( Methods/Functions )

A method/function definition starts with the def keyword, followed by the name of the function, and ends with the end keyword.

方法/函数定义以def关键字开头,后跟函数名称,最后以end关键字end

In Ruby, a function always returns something hence the last statement of a function, whatever it evaluates to, is the returned value.

在Ruby中,函数总是返回某些内容,因此函数的最后一条语句(无论计算结果如何)都是返回值。

Since the last statement is always the returned value, you can explicitly use the return keyword or skip it, it works the same way.

由于最后一条语句始终是返回值,因此可以显式使用return关键字或跳过它,它的工作方式相同。

The following function definitions, though syntactically different, are the same.

以下函数定义尽管在语法上有所不同,但却是相同的。

# function declaration 1
def multiply(param1, param2)
  return param1 * param2
end

# function declaration 2
def multiply(param1, param2)
  param1 * param2
end

面向对象的构造 ( Object-Oriented Constructs )

As I have mentioned, Ruby is purely an object-oriented programming language. It provides a comprehensive syntax to write modules and classes.

正如我已经提到的,Ruby纯粹是一种面向对象的编程语言。 它提供了用于编写模块和类的综合语法。

Apart from writing modules and classes, meta-programming is one of the strongest aspects of Ruby.

除了编写模块和类之外,元编程是Ruby最强大的方面之一。

Though meta-programming is not a subject for beginners, you can think of it as "computer programs who write computer programs" on the go at runtime, know that it is a part of Ruby, and is one of the sharpest tools in a Rubyist's arsenal.

尽管元编程不是初学者的主题,但您可以将其视为运行时随时随地的“编写计算机程序的计算机程序”,知道它是Ruby的一部分,并且是Rubyist的最强大的工具之一。兵工厂。

For now, let us look at how to go about object oriented programming in Ruby.

现在,让我们看一下如何在Ruby中进行面向对象的编程。

分为类定义 (Diving into a Class Definition)

We are going to start with a comprehensive class definition for an employee object, followed by a detailed description and commentary on the code produced forth.

我们将从雇员对象的全面类定义开始,然后是对所产生代码的详细描述和注释。

class Employee

  # change scope to public
  public

  # static class variable
  @@count = 0

  # constructor
  def initialize(name, designation, salary)
    @name = name
    @designation = designation
    @salary = salary
    @@count += 1
  end

  # class method
  def self.count
    @@count
  end

  # getters/setters for name, designation, and salary
  def name
    @name
  end

  def name=(name)
    @name = name
  end

  def designation
    @designation
  end

  def designation=(designation)
    @designation = designation
  end

  def salary
    @salary
  end

  def salary=(salary)
    @salary = salary
  end

  # change scope to private
  private

  def organization
    "Hackers de Anonymous"  
  end

  # change scope to protected
  protected

  def owner
    "We never mention his name!"
  end

end

We start with the class keyword followed by the name of the class which in this case is, Employee.

我们以class关键字开头,后跟class的名称,在本例中为Employee

Inside a class, we can use the public, private, and protected keywords to scope our methods and variables.

在类内部,我们可以使用publicprivateprotected关键字来定义方法和变量的范围。

Since we want to make the next series of methods and variables public, we specify the public scope. Publicly scoped class members are accessible from within and outside the class.

由于我们想将下一个方法和变量系列公开,因此我们指定了公共范围。 可从班级内部和外部访问公共范围的班级成员。

The employee class has a static variable @@count to keep an account of total employee objects. Static variables are declared using @@ followed by the name of the variable.

员工类具有一个静态变量@@count ,用于记录员工总数。 静态变量使用@@声明,后跟变量名称。

initialize is a reserved keyword in Ruby which is used to declare the constructor method for a class.

initialize是Ruby中的保留关键字,用于声明类的构造方法。

For our constructor, we simply pass in the name, designation, and salary of the employee and set the respective instance variables of the same name. Instance variables are declared using @ followed by the name of the variable.

对于我们的构造函数,我们只需要传入雇员的姓名,职务和薪水,然后设置相同名称的各个实例变量即可。 实例变量使用@声明,后跟变量名称。

The next part of the class is a static method defined on the employee class, which simply returns the total count of the employee objects created.

该类的下一部分是在employee类上定义的静态方法,该方法仅返回创建的雇员对象的总数。

Notice how the self keyword has been used.

请注意如何使用self关键字。

In Ruby, a class definition is an instance of the class Class. Our employee class inherits from the object Class so specifying the self keyword gives it the context of the current class, which is the employee class. Thus, our method is defined on the employee class object, and not the employee object.

在Ruby中,类定义是Class的实例。 我们的雇员类继承自对象Class因此指定self关键字将为其提供当前类(雇员类)的上下文。 因此,我们的方法是在雇员类对象上定义的,而不是在雇员对象上定义的。

I am sure this sounds a bit tricky and hard to get your head around so for now, let's keep it simple. Just remember to use the self keyword when declaring class methods.

我相信这听起来有些棘手且难以理解,所以现在让我们保持简单。 只要记住在声明类方法时使用self关键字即可。

The next six methods simply define getters and setters for name, designation, and salary respectively.

接下来的六个方法分别简单地为名称,名称和薪金定义了获取和设置方法。

The getter methods are pretty straight forward. However, notice the = in the setter method's name.

吸气方法很简单。 但是,请注意setter方法名称中的=

The equality symbol in a setter method's name is a Ruby convention that needs to be followed when declaring setter methods. Generally, setter methods are declared using the template def <instance-variable-name>=(<instance-variable-name>).

setter方法名称中的等号是Ruby约定,在声明setter方法时必须遵循。 通常,使用模板def <instance-variable-name>=(<instance-variable-name>)声明setter方法。

Once we are done with the publicly accessible parts of our class, we change the scope to private using the private keyword. It means that the variables and methods that follow are private. Privately scoped class members are accessible from within the class only.

一旦完成了类中可公开访问的部分,就可以使用private关键字将范围更改为private。 这意味着后面的变量和方法是私有的。 私有范围的班级成员只能在班级内部访问。

Finally, towards the end of the class definition, we change the scope to protected. Protected methods are accessible from within child classes.

最后,在类定义的末尾,我们将范围更改为protected。 可从子类内部访问受保护的方法。

Speaking of child classes, in Ruby, classes are inherited using the < operator.

说到子类,在Ruby中,类是使用<运算符继承的。

So, let us say, we wanted to have a SoftwareEngineer class that inherits from the employee class.

所以,让我们说,我们希望有一个从employee类继承的SoftwareEngineer类。

In such a case, our class definition would go as follows:

在这种情况下,我们的类定义将如下所示:

class SoftwareEngineer < Employee

  # code for SoftwareEngineer class

end

Coming back to the employee class, though our class definition is correct and the code works, I would like to introduce a few more Ruby constructs which would greatly simplify our class definition.

回到employee类,尽管我们的类定义是正确的并且代码可以正常工作,但我想介绍更多的Ruby构造,这些构造将大大简化我们的类定义。

The first thing to know is the default scope inside a class is public so you do not have to specify it explicitly.

首先要知道的是,类中的默认范围是公共的,因此您不必显式指定它。

For getter and setter methods, Ruby provides the attr_reader, attr_writer, and attr_accessor functions.

对于getter和setter方法,Ruby提供了attr_readerattr_writerattr_accessor函数。

The attr_reader function is used to specify readable class attributes.

attr_reader函数用于指定可读的类属性。

The attr_writer function is used to specify writable class attributes.

attr_writer函数用于指定可写的类属性。

The attr_accessor function is used to specify class attributes that are both, readable and writable.

attr_accessor函数用于指定可读写的类属性。

All three functions accept symbolized, comma separated attribute names and the getter/setter methods are automatically generated.

这三个函数均接受用逗号分隔的符号化属性名称,并且自动生成getter / setter方法。

Incorporating the above improvements, here is our revised class definition.

结合以上改进,这是我们修订的类定义。

class Employee

  attr_accessor :name, :designation, :salary

  @@count = 0

  def initialize(name, designation, salary)
    @name = name
    @designation = designation
    @salary = salary
    @@count += 1
  end

  def self.count
    @@count
  end

  private

  def organization
    "Hackers de Anonymous"  
  end

  protected

  def owner
    "We never mention his name!"
  end

end

全局和常数 ( Globals and Constants )

If you wish to declare global variables in your program, just prepend the variable name with a $ and the variable will be accessible from anywhere in your program.

如果要在程序中声明全局变量,只需在变量名前加上$ ,即可从程序中的任何位置访问该变量。

$some_global = "some important global value"

Global variables are generally not very famous among programmers because they can make the process of isolating problems very difficult. They can also make debugging your programs harder. Due to these reasons, use global variables sparingly and only in situations, where an alternative is not available.

全局变量通常在程序员中并不是很出名,因为它们会使隔离问题的过程变得非常困难。 它们还会使调试程序变得更加困难。 由于这些原因,请谨慎使用全局变量,并且仅在没有替代方法的情况下使用。

Similarly, constants can be declared by capitalizing the first letter of their name.

同样,可以通过将常量名称的首字母大写来声明常量。

Constant = 5

Though the Ruby interpreter does not ensure that a constant's value remains unchanged, it will produce a warning in case you re-declare a constant.

尽管Ruby解释器不能确保常量的值保持不变,但是如果您重新声明常量,它将产生警告。

The following code snippet produces the already initialized constant warning.

以下代码段将生成already initialized constant警告。

Constant = 5

puts "Do some great stuff!"

Constant = 10

Generally, by convention, constant names are fully capitalized.

通常,按照惯例,常量名称要全大写。

CONSTANT = 5

例外情况 ( Exceptions )

Code that may produce an exception is wrapped inside a begin/rescue block.

可能产生异常的代码被包装在begin/rescue块中。

Let us write the famous "division by zero" code to see exception handling in action.

让我们编写著名的“零除”代码以查看实际的异常处理。

result= 100 / 0

puts result

The above code produces the divided by 0 (ZeroDivisionError) error.

上面的代码产生divided by 0 (ZeroDivisionError)错误。

If you were say, writing a calculator application in Ruby, handling such exceptions would be paramount to your application functioning gracefully.

如果说用Ruby编写计算器应用程序,那么处理此类异常将对您的应用程序正常运行至关重要。

begin
  result = 100 / 0
  puts result
rescue StandardError => e
  puts "You cannot divide by 0"
end 

Now, when the exception is raised, control is immediately shifted to the rescue block and your code outputs You cannot divide by 0.

现在,当引发异常时,控制权立即移至救援块,并且代码输出You cannot divide by 0

Also, all exceptions inherit from the base class Exception so in your code, you can rescue Exception instead of StandardError.

同样,所有异常都从基类Exception继承,因此在您的代码中,您可以抢救Exception而不是StandardError

However, the problem with that approach is Exception is at the top of the food chain so if you rescue it, your code would just swallow everything, even the syntax errors.

但是,这种方法的问题在于Exception位于食物链的顶部,因此,如果您将其救出,代码将吞没所有内容,甚至语法错误。

Luckily, as mentioned, you have a toned down version in the StandardError class that makes sure your code only catches the useful exceptions.

幸运的是,如上所述,您在StandardError类中有一个精简版本,可确保您的代码仅捕获有用的异常。

The last bit of useful information regarding exceptions is the ensure block.

关于异常的有用信息的最后一点是ensure块。

The ensure block encapsulates code that executes irrespective of whether the exception occurs or not.

确保块封装了无论是否发生异常都执行的代码。

Revising our earlier code with the ensure block.

使用sure块修改我们之前的代码。

begin
  result = 100 / 0
  puts result
rescue StandardError => e
  puts "You cannot divide by 0"
ensure
  puts "Exception or no exception, now we here!"
end 

使用分布式代码 ( Working with Distributed Code )

Ruby has the extend, include, load, and require keywords to incorporate your code from external files.

Ruby具有extendincludeloadrequire关键字,以从外部文件合并您的代码。

Let us write a very simple class that we can use to understand how load and require works.

让我们编写一个非常简单的类,我们可以使用它来了解负载和需求的工作方式。

Create a new file named gandalf.rb and add the following code.

创建一个名为gandalf.rb的新文件,并添加以下代码。

class Gandalf
  def speak
    puts "You shall not pass!"
  end
end

加载 (load)

When you use the load keyword to load a file, you need to provide the complete filename otherwise you will receive a cannot load such file error.

当使用load关键字加载文件时,需要提供完整的文件名,否则将收到cannot load such file错误。

At the same location where you created the gandalf.rb file, create another file test.rb and add the following code.

在创建gandalf.rb文件的位置,创建另一个文件test.rb并添加以下代码。

load'./gandalf.rb'

Gandalf.new.speak

The code produces the output You shall not pass! which means our external class was loaded successfully.

代码产生输出, You shall not pass! 这意味着我们的外部类已成功加载。

When you load a file, it is loaded as many times as you load it.

加载文件时,该文件的加载次数与加载的次数相同。

For example, let us say you have three classes A, B and C. Class A and B both load class C. When you load class A and B, class C will be loaded twice into memory.

例如,假设您有三个类A,B和C。类A和B都加载了类C。当您加载类A和B时,类C将被两次加载到内存中。

Of course this sounds a bit inefficient, which is where the require keyword comes in.

当然,这听起来有点低效,这是require关键字出现的地方。

要求 (require)

When you use require to load a file, it is loaded only once into memory irrespective of how many times you require it.

使用require加载文件时,无论您需要多少次,该文件仅被加载到内存中一次。

You can also skip the file extension if it's .rb when you require a file.

当您需要文件扩展名是.rb时,也可以跳过该文件扩展名。

require './gandalf'

Gandalf.new.speak

混入 (Mix-Ins)

Before we move to understanding include and extend, you should know a Ruby concept known as "mix-in".

在开始理解includeextend ,您应该了解一个称为“ mix-in”的Ruby概念。

A mix-in is simply modularized code that can be merged into your classes.

混合是简单的模块化代码,可以合并到您的类中。

Let's walk through an example.

让我们来看一个例子。

Suppose you are writing classes for different animals in the animal kingdom.

假设您正在为动物界中的不同动物编写课程。

Since all animals eat, you need an eat instance method on all of them. So, if we have a Cat, Dog, and Human class, our design would go something like.

由于所有动物都进食,因此您需要对所有动物进行eat实例方法。 因此,如果我们有CatDogHuman类,我们的设计将类似于。

# file: cat.rb
class Cat
  def eat
    puts "I am chewing!"
  end
end

# file: dog.rb
class Dog
  def eat
    puts "I am chewing!"
  end
end

# file: human.rb
class Human
  def eat
    puts "I am chewing!"
  end
end

Code repetition is never a wise move and since Ruby does not support multiple inheritance, this seems to be the only option.

代码重复绝不是明智之举,并且由于Ruby不支持多重继承,因此这似乎是唯一的选择。

模块化代码 (Modularizing Code)

First, we are going to move the eat method into a separate module named BasicFunctions. While we are at it, just for demonstration, let's throw in the drink, and sleep methods as well.

首先,我们将eat方法移至名为BasicFunctions的单独模块中。 在演示的同时,我们只是为了示范,我们还请drink ,并sleep

Create a file (at the same location where you created cat.rb, dog.rb, and human.rb) named basic_functions.rb and add the following code.

创建一个名为basic_functions.rb的文件(在创建cat.rbdog.rbhuman.rb ),并添加以下代码。

module BasicFunctions
  def eat
    puts "I am chewing!"
  end

  def drink
    puts "Slurp! Slurp! Slurp!"
  end

  def sleep
    puts "Zzzzzzzzzzzzzzzzz!"
  end
end

Let's get back to understanding include and extend then, shall we?

让我们回到对includeextend理解上,对吧?

包括 (include)

When you use the include keyword to add external code into your classes, the methods you define in your module are added as instance methods to your class.

当您使用include关键字将外部代码添加到您的类中时,您在模块中定义的方法将作为实例方法添加到您的类中。

Instead of repeating code, we can now re-write our Cat, Dog, and Human class using include.

现在,无需重复代码,我们可以使用include重写Cat,Dog和Human类。

# file: cat.rb

require './basic_functions'

class Cat
  include BasicFunctions
end

# file: dog.rb

require './basic_functions'

Class Dog
  include BasicFunctions
end

# file: human.rb

require './basic_functions'

Class Human
  include BasicFunctions
end

And here is the Cat, Dog, and Human class in action.

这是行动中的猫,狗和人类课程。

require './cat
require './dog'
require './human'

cat = Cat.new
cat.eat
cat.drink
cat.sleep

dog = Dog.new
dog.eat
dog.drink
dog.sleep

human = Human.new
human.eat
human.drink
human.sleep

延伸 (extend)

The extend keyword works like the include keyword, the only difference is the methods are added as class methods to your class.

extend关键字的工作方式类似于include关键字,唯一的区别是方法是作为类方法添加到您的类中的。

require './basic_functions'

class Cat
  extend BasicFunctions
end

Class Dog
  extend BasicFunctions
end

Class Human
  extend BasicFunctions
end

Since eat, drink, and sleep are now class methods, we do not need object instances anymore.

由于饮食和睡眠现在是类方法,因此我们不再需要对象实例。

require './cat
require './dog'
require './human'

Cat.eat
Cat.drink
Cat.sleep

Dog.eat
Dog.drink
Dog.sleep

Human.eat
Human.drink
Human.sleep

使用Ruby ( Using Ruby Gems )

Ruby gems are packaged modules/classes that can be used to extend Ruby's core functionality.

Ruby gem是打包的模块/类,可用于扩展Ruby的核心功能。

If you require certain functionality in your Ruby applications, you can search for a gem and use it instead of writing the code yourself.

如果您在Ruby应用程序中需要某些功能,则可以搜索gem并使用它,而不用自己编写代码。

For example, let's say you are building an HTML email parser that automatically extracts certain information from incoming HTML emails and dumps them into the database.

例如,假设您正在构建一个HTML电子邮件解析器,该解析器会自动从传入HTML电子邮件中提取某些信息并将其转储到数据库中。

In such a scenario, instead of writing complex parsing logic, you can use a markup parsing gem such as Nokogiri.

在这种情况下,您可以使用标记解析gem(例如Nokogiri)来代替编写复杂的解析逻辑。

First, install the gem from the command line.

首先,从命令行安装gem。

$ geminstall nokogiri

Then, in your code file, require the gem and you are good to go.

然后,在您的代码文件中,要求使用gem,您就可以使用了。

require 'rubygems' # required in Ruby versions less than 1.9.*
require 'nokogiri' # require the nokogiri gem

# your code that uses the nokogiri gem

The official Ruby gems repository has millions of gems that you can search from.

官方的Ruby gems存储库拥有数百万个可以搜索的宝石。

If you are using a Ruby version lesser than 1.9.*, you might have to setup Ruby gems separately. The official Ruby gems installation guide explains how to do it.

如果您使用的Ruby版本低于1.9。*,则可能必须单独设置Ruby gem。 官方的Ruby gems安装指南介绍了操作方法。

幕布 ( Curtains )

Our run through of the Ruby language is almost at it's end but hopefully, not your love for the Ruby programming language.

我们对Ruby语言的学习几乎快结束了,但希望不是您对Ruby编程语言的热爱。

Ruby was created to make programming fun again and as you work with it over the years, you will realize the creators of Ruby have succeeded emphatically in that endeavour.

Ruby的创建再次使编程变得有趣,并且当您多年来与之合作时,您将意识到Ruby的创建者在这一努力上取得了圆满成功。

Where to go from here, you did ask.

你问过从这里去哪里。

I have found that there are multiple ways to do a single thing in Ruby so it can get hard at times, to consolidate code from all the different developers. Perhaps, reading a Ruby coding standards guide next would be a good idea?

我发现在Ruby中有多种方法可以做一件事情,因此有时很难合并来自所有不同开发人员的代码。 也许,接下来阅读Ruby编码标准指南会是一个好主意吗?

I hope you found this tutorial interesting and knowledgeable. Until my next piece, happy coding!

我希望您发现本教程有趣且知识丰富。 直到我的下一篇文章,祝您编程愉快!

翻译自: https://scotch.io/tutorials/a-crash-course-in-ruby

ruby中argv

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值