零基础学习ruby_学习Ruby:从零到英雄

零基础学习ruby

“Ruby is simple in appearance, but is very complex inside, just like our human body.” — Matz, creator of the Ruby programming language

“ Ruby的外观很简单,但是内部却非常复杂,就像我们的人体一样。” — Matz ,Ruby编程语言的创建者

Why learn Ruby?

为什么要学习Ruby?

For me, the first reason is that it’s a beautiful language. It’s natural to code and it always expresses my thoughts.

对我来说,第一个原因是这是一门优美的语言。 编写代码很自然,并且总是表达我的想法。

The second — and main — reason is Rails: the same framework that Twitter, Basecamp, Airbnb, Github, and so many companies use.

第二个也是主要的原因是Rails :Twitter,Basecamp,Airbnb,Github和许多公司使用的框架相同。

简介/历史 (Introduction/History)

Ruby is “A 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-lang.org

Ruby是一种动态的,开放源代码的编程语言,其重点是简单性和生产率。 它具有优雅的语法,易于阅读且易于编写。” — ruby-lang.org

Let’s get started with some basics!

让我们开始一些基础知识!

变数 (Variables)

You can think about a variable as a word that stores a value. Simple as that.

您可以将变量视为存储值的单词。 就那么简单。

In Ruby it’s easy to define a variable and set a value to it. Imagine you want to store the number 1 in a variable called one. Let’s do it!

在Ruby中,很容易定义变量并为其设置值。 假设您想将数字1存储在名为one的变量中。 我们开始做吧!

one = 1

How simple was that? You just assigned the value 1 to a variable called one.

那有多简单? 您刚刚将值1分配给了名为1的变量。

two = 2
some_number = 10000

You can assign a value to whatever variable you want. In the example above, a two variable stores an integer of 2 and some_number stores 10,000.

您可以将值分配给所需的任何变量。 在上面的示例中, 两个变量存储2的整数, some_number存储10,000。

Besides integers, we can also use booleans (true/false), strings, symbols, float, and other data types.

除了整数外,我们还可以使用布尔值(true / false),字符串, symbols ,float和其他数据类型。

# booleans
true_boolean = true
false_boolean = false# string
my_name = "Leandro Tk"# symbol
a_symbol = :my_symbol# float
book_price = 15.80

条件语句:控制流 (Conditional Statements: Control Flow)

Conditional statements evaluate true or false. If something is true, it executes what’s inside the statement. For example:

条件语句评估是非。 如果为真,则执行语句中的内容。 例如:

if trueputs "Hello Ruby If"
endif 2 > 1puts "2 is greater than 1"
end

2 is greater than 1, so the puts code is executed.

2大于1,因此执行puts代码。

This else statement will be executed when the if expression is false:

当if表达式为false时,将执行else语句:

if 1 > 2puts "1 is greater than 2"
elseputs "1 is not greater than 2"
end

1 is not greater than 2, so the code inside the else statement will be executed.

1不大于2,因此将执行else语句中的代码。

There’s also the elsif statement. You can use it like this:

还有elsif语句。 您可以像这样使用它:

if 1 > 2puts "1 is greater than 2"
elsif 2 > 1puts "1 is not greater than 2"
elseputs "1 is equal to 2"
end

One way I really like to write Ruby is to use an if statement after the code to be executed:

我真的很喜欢编写Ruby的一种方法是在要执行的代码后使用if语句:

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

It is so beautiful and natural. It is idiomatic Ruby.

它是如此美丽和自然。 它是惯用的Ruby。

循环/迭代器 (Looping/Iterator)

In Ruby we can iterate in so many different forms. I’ll talk about three iterators: while, for and each.

在Ruby中,我们可以以许多不同的形式进行迭代。 我将讨论三个迭代器:while,for和each。

While looping: As long as the statement is true, the code inside the block will be executed. So this code will print the number from 1 to 10:

循环时:只要该语句为true,就将执行块中的代码。 因此,此代码将打印从1到10的数字:

num = 1while num <= 10puts numnum += 1
end

For looping: You pass the variable num to the block and the for statement will iterate it for you. This code will print the same as while code: from 1 to 10:

For循环:将变量num传递给块,for语句将为您迭代。 此代码的打印方式与while代码相同:从1到10:

for num in 1...10puts num
end

Each iterator: I really like the each iterator. For an array of values, it’ll iterate one by one, passing the variable to the block:

每个迭代器:我真的很喜欢每个迭代器。 对于值数组,它将一步一步地迭代,并将变量传递给块:

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

You may be asking what the difference is between the each iterator and for looping. The main difference is that the each iterator only maintains the variable inside the iteration block, whereas for looping allows the variable to live on outside the block.

您可能会问,每个迭代器和循环之间有什么区别。 主要区别在于,每个迭代器仅将变量保留在迭代块内部,而对于循环,则允许变量驻留在块外部。

# for vs each# for looping
for num in 1...5puts num
endputs num # => 5# each iterator
[1, 2, 3, 4, 5].each do |num|puts num
endputs num # => undefined local variable or method `n' for main:Object (NameError)

数组:集合/列表/数据结构 (Array: Collection/List/Data Structure)

Imagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 3, 4, 5 …

假设您要将整数1存储在变量中。 但也许现在您想存储2和3、4、5…

Do I have a way to store all the integers that I want, but not in millions of variables? Ruby has an answer!

我是否可以存储所需的所有整数,但不能存储数百万个变量? Ruby有一个答案!

Array is a collection that can be used to store a list of values (like these integers). So let’s use it!

数组是一个集合,可用于存储值列表(如这些整数)。 因此,让我们使用它!

my_integers = [1, 2, 3, 4, 5]

It is really simple. We created an array and stored it in my_integer.

真的很简单。 我们创建了一个数组并将其存储在my_integer中

You may be asking, “How can I get a value from this array?” Great question. Arrays have a concept called index. The first element gets the index 0 (zero). The second gets 1, and so on. You get the idea!

您可能会问:“如何从该数组中获取值?” 好问题。 数组有一个称为索引的概念。 第一个元素的索引为0(零)。 第二个为1,依此类推。 你明白了!

Using the Ruby syntax, it’s simple to understand:

使用Ruby语法,很容易理解:

my_integers = [5, 7, 1, 3, 4]
print my_integers[0] # 5
print my_integers[1] # 7
print my_integers[4] # 4

Imagine you want to store strings instead of integers, like a list of your relatives’ names. Mine would be something like this:

假设您想存储字符串而不是整数,例如您的亲戚名字列表。 我的会是这样的:

relatives_names = ["Toshiaki","Juliana","Yuji","Bruno","Kaio"
]print relatives_names[4] # Kaio

Works the same way as integers. Nice!

与整数的工作方式相同。 真好!

We just learned how array indices works. Now let’s add elements to the array data structure (items to the list).

我们刚刚了解了数组索引的工作原理。 现在让我们将元素添加到数组数据结构(列表中的项目)。

The most common methods to add a new value to an array are push and <<.

向数组添加新值的最常见方法是push和<<。

Push is super simple! You just need to pass the element (The Effective Engineer) as the push parameter:

推送超级简单! 您只需要传递元素(有效工程师)作为push参数:

bookshelf = []
bookshelf.push("The Effective Engineer")
bookshelf.push("The 4 hours work week")
print bookshelf[0] # The Effective Engineer
print bookshelf[1] # The 4 hours work week

The << method is just slightly different:

<<方法略有不同:

bookshelf = []
bookshelf << "Lean Startup"
bookshelf << "Zero to One"
print bookshelf[0] # Lean Startup
print bookshelf[1] # Zero to One

You may ask, “But it doesn’t use the dot notation like other methods do. How could it be a method?” Nice question! Writing this:

您可能会问:“但是它不像其他方法那样使用点符号。 这怎么可能是一种方法?” 好问题! 写这个:

bookshelf << "Hooked"

…is similar to writing this:

…类似于编写此代码:

bookshelf.<<("Hooked")

Ruby is so great, huh?

露比真是太好了吧?

Well, enough arrays. Let’s talk about another data structure.

好吧,足够的数组。 让我们谈谈另一种数据结构。

哈希:键值数据结构/词典集合 (Hash: Key-Value Data Structure/Dictionary Collection)

We know that arrays are indexed with numbers. But what if we don’t want to use numbers as indices? Some data structures can use numeric, string, or other types of indices. The hash data structure is one of them.

我们知道数组是用数字索引的。 但是,如果我们不想使用数字作为索引怎么办? 某些数据结构可以使用数字,字符串或其他类型的索引。 哈希数据结构就是其中之一。

Hash is a collection of key-value pairs. It looks like this:

哈希是键值对的集合。 看起来像这样:

hash_example = {"key1" => "value1","key2" => "value2","key3" => "value3"
}

The key is the index pointing to the value. How do we access the hash value? Using the key!

关键是指向值的索引。 我们如何访问哈希值? 使用钥匙!

Here’s a hash about me. My name, nickname, and nationality are the hash’s keys.

这是关于我的哈希。 我的名字,昵称和国籍是哈希的键。

hash_tk = {"name" => "Leandro","nickname" => "Tk","nationality" => "Brazilian"
}print "My name is #{hash_tk["name"]}" # My name is Leandro
print "But you can call me #{hash_tk["nickname"]}" # But you can call me Tk
print "And by the way I'm #{hash_tk["nationality"]}" # And by the way I'm Brazilian

In the above example I printed a phrase about me using all the values stored in the hash.

在上面的示例中,我使用散列中存储的所有值打印了一个关于我的短语。

Another cool thing about hashes is that we can use anything as the value. I’ll add the key “age” and my real integer age (24).

关于哈希的另一个很酷的事情是,我们可以使用任何东西作为值。 我将添加密钥“ age”和我的真实整数年龄(24)。

hash_tk = {"name" => "Leandro","nickname" => "Tk","nationality" => "Brazilian","age" => 24
}print "My name is #{hash_tk["name"]}" # My name is Leandro
print "But you can call me #{hash_tk["nickname"]}" # But you can call me Tk
print "And by the way I'm #{hash_tk["age"]} and #{hash_tk["nationality"]}" # And by the way I'm 24 and Brazilian

Let’s learn how to add elements to a hash. The key pointing to a value is a big part of what hash is — and the same goes for when we want to add elements to it.

让我们学习如何将元素添加到哈希中。 指向值的关键是哈希值的重要组成部分,当我们想向其添加元素时也是如此。

hash_tk = {"name" => "Leandro","nickname" => "Tk","nationality" => "Brazilian"  
}hash_tk["age"] = 24
print hash_tk # { "name" => "Leandro", "nickname" => "Tk", "nationality" => "Brazilian", "age" => 24 }

We just need to assign a value to a hash key. Nothing complicated here, right?

我们只需要为哈希键分配一个值即可。 这里没什么复杂的,对吧?

迭代:遍历数据结构 (Iteration: Looping Through Data Structures)

The array iteration is very simple. Ruby developers commonly use the each iterator. Let’s do it:

数组迭代非常简单。 Ruby开发人员通常使用each迭代器。 我们开始做吧:

bookshelf = ["The Effective Engineer","The 4 hours work week","Zero to One","Lean Startup","Hooked"
]bookshelf.each do |book|puts book
end

The each iterator works by passing array elements as parameters in the block. In the above example, we print each element.

每个迭代器通过将数组元素作为参数传递到块中来工作。 在上面的示例中,我们打印每个元素。

For hash data structure, we can also use the each iterator by passing two parameters to the block: the key and the value. Here’s an example:

对于哈希数据结构,我们还可以通过将两个参数传递给块来使用每个迭代器:键和值。 这是一个例子:

hash = { "some_key" => "some_value" }
hash.each { |key, value| puts "#{key}: #{value}" } # some_key: some_value

We named the two parameters as key and value, but it’s not necessary. We can name them anything:

我们将两个参数分别命名为键和值,但这不是必需的。 我们可以为它们命名:

hash_tk = {"name" => "Leandro","nickname" => "Tk","nationality" => "Brazilian","age" => 24
}hash_tk.each do |attribute, value|puts "#{attribute}: #{value}"
end

You can see we used attribute as a parameter for the hash key and it works properly. Great!

您可以看到我们使用属性作为哈希键的参数,并且可以正常工作。 大!

类和对象 (Classes & Objects)

As an object oriented programming language, Ruby uses the concepts of class and object.

作为一种面向对象的编程语言,Ruby使用类和对象的概念。

“Class” is a way to define objects. In the real world there are many objects of the same type. Like vehicles, dogs, bikes. Each vehicle has similar components (wheels, doors, engine).

“类”是定义对象的一种方法。 在现实世界中,有许多相同类型的对象。 像车辆,狗,自行车一样。 每辆车都有相似的组件(车轮,门,发动机)。

“Objects” have two main characteristics: data and behavior. Vehicles have data like number of wheels and number of doors. They also have behavior like accelerating and stopping.

“对象”具有两个主要特征:数据和行为。 车辆具有车轮数量和门数量等数据。 它们也有加速和停止之类的行为。

In object oriented programming we call data “attributes” and behavior “methods.”

在面向对象的编程中,我们将数据称为“属性”,将行为称为“方法”。

Data = Attributes

数据=属性

Behavior = Methods

行为=方法

Ruby面向对象的编程模式:开 (Ruby Object Oriented Programming Mode: On)

Let’s understand Ruby syntax for classes:

让我们了解类的Ruby语法:

class Vehicle
end

We define Vehicle with class statement and finish with end. Easy!

我们用class语句定义Vehicle并以end结尾。 简单!

And objects are instances of a class. We create an instance by calling the .new method.

对象是类的实例。 我们通过调用.new方法来创建实例。

vehicle = Vehicle.new

Here vehicle is an object (or instance) of the class Vehicle.

这里的Vehicle是Vehicle类的对象(或实例)。

Our vehicle class will have 4 attributes: Wheels, type of tank, seating capacity, and maximum velocity.

我们的车辆类别将具有4个属性:车轮,油箱类型,座位容量和最大速度。

Let’s define our class Vehicle to receive data and instantiate it.

让我们定义我们的Vehicle类来接收数据并实例化它。

class Vehicledef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityend
end

We use the initialize method. We call it a constructor method so when we create the vehicle object, we can define its attributes.

我们使用initialize方法。 我们将其称为构造函数方法,以便在创建车辆对象时可以定义其属性。

Imagine that you love the Tesla Model S and want to create this kind of object. It has 4 wheels. Its tank type is electric energy. It has space for 5 seats and a maximum velocity is 250km/hour (155 mph). Let’s create the object tesla_model_s! :)

想象一下,您喜欢特斯拉Model S,并且想要创建这种对象。 它有4个轮子。 它的储罐类型是电能。 它可以容纳5个座位,最大速度为250公里/小时(155英里/小时)。 让我们创建对象tesla_model_s! :)

tesla_model_s = Vehicle.new(4, 'electric', 5, 250)

4 wheels + electric tank + 5 seats + 250km/hour maximum speed = tesla_model_s.

4轮+电动油箱+ 5个座位+ 250km /小时的最高速度= tesla_model_s。

tesla_model_s
# => <Vehicle:0x0055d516903a08 @number_of_wheels=4, @type_of_tank="electric", @seating_capacity=5, @maximum_velocity=250>

We’ve set the Tesla’s attributes. But how do we access them?

我们已经设置了特斯拉的属性。 但是,我们如何访问它们?

We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it!

我们向对象发送一条消息,询问有关它们的信息。 我们称其为方法。 这是对象的行为。 让我们实现它!

class Vehicledef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityenddef number_of_wheels@number_of_wheelsenddef set_number_of_wheels=(number)@number_of_wheels = numberend
end

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it “getter” and “setter.” First we get the attribute value, and second, we set a value for the attribute.

这是两个方法的实现:number_of_wheels和set_number_of_wheels。 我们称其为“ getter”和“ setter”。 首先,我们获得属性值,其次,为属性设置一个值。

In Ruby, we can do that without methods using attr_reader, attr_writer and attr_accessor. Let’s see it with code!

在Ruby中,无需使用attr_reader,attr_writer和attr_accessor的方法就可以做到这一点。 我们来看一下代码吧!

  • attr_reader: implements the getter method

    attr_reader:实现getter方法
class Vehicleattr_reader :number_of_wheelsdef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityend
endtesla_model_s = Vehicle.new(4, 'electric', 5, 250)
tesla_model_s.number_of_wheels # => 4
  • attr_writer: implements the setter method

    attr_writer:实现setter方法
class Vehicleattr_writer :number_of_wheelsdef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityend
end# number_of_wheels equals 4
tesla_model_s = Vehicle.new(4, 'electric', 5, 250)
tesla_model_s # => <Vehicle:0x0055644f55b820 @number_of_wheels=4, @type_of_tank="electric", @seating_capacity=5, @maximum_velocity=250># number_of_wheels equals 3
tesla_model_s.number_of_wheels = 3
tesla_model_s # => <Vehicle:0x0055644f55b820 @number_of_wheels=3, @type_of_tank="electric", @seating_capacity=5, @maximum_velocity=250>
  • attr_accessor: implements both methods

    attr_accessor:实现两种方法
class Vehicleattr_accessor :number_of_wheelsdef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityend
end# number_of_wheels equals 4
tesla_model_s = Vehicle.new(4, 'electric', 5, 250)
tesla_model_s.number_of_wheels # => 4# number_of_wheels equals 3
tesla_model_s.number_of_wheels = 3
tesla_model_s.number_of_wheels # => 3

So now we’ve learned how to get attribute values, implement the getter and setter methods, and use attr (reader, writer, and accessor).

因此,现在我们已经学习了如何获取属性值,实现getter和setter方法以及如何使用attr(读取器,写入器和访问器)。

We can also use methods to do other things — like a “make_noise” method. Let’s see it!

我们还可以使用方法来做其他事情-例如“ make_noise”方法。 让我们来看看它!

class Vehicledef initialize(number_of_wheels, type_of_tank, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@type_of_tank = type_of_tank@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityenddef make_noise"VRRRRUUUUM"end
end

When we call this method, it just returns a string “VRRRRUUUUM”.

当我们调用此方法时,它仅返回字符串“ VRRRRUUUUM”。

v = Vehicle.new(4, 'gasoline', 5, 180)
v.make_noise # => "VRRRRUUUUM"

封装:隐藏信息 (Encapsulation: Hiding Information)

Encapsulation is a way to restrict direct access to objects’ data and methods. At the same time it facilitates operation on that data (objects’ methods).

封装是一种限制直接访问对象的数据和方法的方法。 同时,它便于对该数据进行操作(对象的方法)。

Encapsulation can be used to hide data members and members function…Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.

封装可用于隐藏数据成员和成员函数……封装意味着对象的内部表示形式通常在对象定义之外的视图中隐藏。

— Wikipedia

— 维基百科

So all internal representation of an object is hidden from the outside, only the object can interact with its internal data.

因此,对象的所有内部表示都从外部隐藏,只有对象可以与其内部数据进行交互。

In Ruby we use methods to directly access data. Let’s see an example:

在Ruby中,我们使用方法直接访问数据。 让我们来看一个例子:

class Persondef initialize(name, age)@name = name@age  = ageend
end

We just implemented this Person class. And as we’ve learned, to create the object person, we use the new method and pass the parameters.

我们刚刚实现了此Person类。 正如我们所了解的,要创建对象人,我们将使用新方法并传递参数。

tk = Person.new("Leandro Tk", 24)

So I created me! :) The tk object! Passing my name and my age. But how can I access this information? My first attempt is to call the name and age methods.

所以我创造了我! :) tk对象! 传递我的名字和年龄。 但是我该如何获取这些信息? 我的第一次尝试是调用name和age方法。

tk.name
> NoMethodError: undefined method `name' for #<Person:0x0055a750f4c520 @name="Leandro Tk", @age=24>

We can’t do it! We didn’t implement the name (and the age) method.

我们做不到! 我们没有实现名称(和年龄)方法。

Remember when I said “In Ruby we use methods to directly access data?” To access the tk name and age we need to implement those methods on our Person class.

还记得我说过“在Ruby中,我们使用方法直接访问数据吗?” 要访问tk名称和年龄,我们需要在Person类上实现这些方法。

class Persondef initialize(name, age)@name = name@age  = ageenddef name@nameenddef age@ageend
end

Now we can directly access this information. With encapsulation we can ensure that the object (tk in this case) is only allowed to access name and age. The internal representation of the object is hidden from the outside.

现在我们可以直接访问此信息。 通过封装,我们可以确保仅允许对象(在这种情况下为tk)访问名称和年龄。 对象的内部表示从外部隐藏。

继承:行为和特征 (Inheritance: behaviors and characteristics)

Certain objects have something in common. Behavior and characteristics.

某些对象有一些共同点。 行为和特征。

For example, I inherited some characteristics and behaviors from my father — like his eyes and hair. And behaviors like impatience and introversion.

例如,我从父亲那里继承了一些特征和行为,例如他的眼睛和头发。 还有不耐烦和内向的行为。

In object oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

在面向对象的编程中,类可以从另一个类继承通用特性(数据)和行为(方法)。

Let’s see another example and implement it in Ruby.

让我们来看另一个示例,并在Ruby中实现它。

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car.

想像一辆汽车。 车轮数量,座位容量和最大速度都是汽车的属性。

class Carattr_accessor :number_of_wheels, :seating_capacity, :maximum_velocitydef initialize(number_of_wheels, seating_capacity, maximum_velocity)@number_of_wheels = number_of_wheels@seating_capacity = seating_capacity@maximum_velocity = maximum_velocityend
end

Our Car class implemented! :)

我们的汽车课已实施! :)

my_car = Car.new(4, 5, 250)
my_car.number_of_wheels # 4
my_car.seating_capacity # 5
my_car.maximum_velocity # 250

Instantiated, we can use all methods created! Nice!

实例化后,我们可以使用创建的所有方法! 真好!

In Ruby, we use the < operator to show a class inherits from another. An ElectricCar class can inherit from our Car class.

在Ruby中,我们使用<运算符显示一个从另一个继承的类。 ElectricCar类可以从我们的Car类继承。

class ElectricCar < Car
end

Simple as that! We don’t need to implement the initialize method and any other method, because this class already has it (inherited from the Car class). Let’s prove it!

就那么简单! 我们不需要实现initialize方法和任何其他方法,因为此类已经拥有了(从Car类继承)。 让我们证明一下!

tesla_model_s = ElectricCar.new(4, 5, 250)
tesla_model_s.number_of_wheels # 4
tesla_model_s.seating_capacity # 5
tesla_model_s.maximum_velocity # 250

Beautiful!

美丽!

模块:工具箱 (Module: A Toolbox)

We can think of a module as a toolbox that contains a set of constants and methods.

我们可以将模块视为包含一组常量和方法的工具箱。

An example of a Ruby module is Math. We can access the constant PI:

Ruby模块的一个示例是Math。 我们可以访问常量PI:

Math::PI # > 3.141592653589793

And the .sqrt method:

和.sqrt方法:

Math.sqrt(9) # 3.0

And we can implement our own module and use it in classes. We have a RunnerAthlete class:

我们可以实现自己的模块,并在类中使用它。 我们有一个RunnerAthlete类:

class RunnerAthletedef initialize(name)@name = nameend
end

And implement a module Skill to have the average_speed method.

并实现模块Skill具有average_speed方法。

module Skilldef average_speedputs "My average speed is 20mph"end
end

How do we add the module to our classes so it has this behavior (average_speed method)? We just include it!

我们如何将模块添加到类中,使其具有此行为(average_speed方法)? 我们只包含它!

class RunnerAthleteinclude Skilldef initialize(name)@name = nameend
end

See the “include Skill”! And now we can use this method in our instance of RunnerAthlete class.

请参阅“包含技能”! 现在,我们可以在RunnerAthlete类的实例中使用此方法。

mohamed = RunnerAthlete.new("Mohamed Farah")
mohamed.average_speed # "My average speed is 20mph"

Yay! To finish modules, we need to understand the following:

好极了! 要完成模块,我们需要了解以下内容:

  • A module can have no instances.

    模块不能有实例。
  • A module can have no subclasses.

    模块不能有子类。
  • A module is defined by module…end.

    模块由模块…结束定义。

结语! (Wrapping Up!)

We learned A LOT of things here!

我们在这里学到了很多东西!

  • How Ruby variables work

    Ruby变量如何工作
  • How Ruby conditional statements work

    Ruby条件语句如何工作
  • How Ruby looping & iterators work

    Ruby循环和迭代器如何工作
  • Array: Collection | List

    数组:集合| 清单
  • Hash: Key-Value Collection

    哈希:键值集合
  • How we can iterate through this data structures

    我们如何遍历此数据结构
  • Objects & Classes

    对象和类
  • Attributes as objects’ data

    属性作为对象的数据
  • Methods as objects’ behavior

    方法作为对象的行为
  • Using Ruby getters and setters

    使用Ruby的getter和setter
  • Encapsulation: hiding information

    封装:隐藏信息
  • Inheritance: behaviors and characteristics

    继承:行为和特征
  • Modules: a toolbox

    模块:工具箱

而已 (That’s it)

Congrats! You completed this dense piece of content about Ruby! We learned a lot here. Hope you liked it.

恭喜! 您已经完成了有关Ruby的大量内容! 我们在这里学到了很多东西。 希望你喜欢。

Have fun, keep learning, and always keep coding!

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

My Twitter & Github. ☺

我的Twitter和Github 。 ☺

翻译自: https://www.freecodecamp.org/news/learning-ruby-from-zero-to-hero-90ad4eecc82d/

零基础学习ruby

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/395239.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows同时启动多个微信

1、创建mychat.bat文件(文件名任意)&#xff0c;输入以下代码&#xff0c;其中"C:\Program Files (x86)\Tencent\WeChat\"为微信的安装路径。以下示例为同时启动两个微信 start/d "C:\Program Files (x86)\Tencent\WeChat\" Wechat.exe start/d "C:\P…

mysql date time year_YEAR、DATE、TIME、DATETIME和TIMESTAMP详细介绍[MySQL数据类型]

为了方便在数据库中存储日期和时间&#xff0c;MySQL提供了表示日期和时间的数据类型&#xff0c;分别是YEAR、DATE、TIME、DATETIME和TIMESTAMP。下面列举了这些MSL中日期和时间数据类型所对应的字节数、取值范围、日期格式以及零值。从上图中可以看出&#xff0c;每种日期和时…

九度oj 题目1380:lucky number

题目描述&#xff1a;每个人有自己的lucky number&#xff0c;小A也一样。不过他的lucky number定义不一样。他认为一个序列中某些数出现的次数为n的话&#xff0c;都是他的lucky number。但是&#xff0c;现在这个序列很大&#xff0c;他无法快速找到所有lucky number。既然这…

安装Tengine

1.安装VMware2.安装CentOS6.53.配置网络a.修改 /etc/sysconfig/network-scripts/ifcfg-eth0配置文件,添加如下内容DEVICEeth0HWADDR00:0C:29:96:01:6BTYPEEthernetUUID41cbd943-024b-4341-ac7a-e4d2142b4938ONBOOTyesNM_CONTROLLEDyesBOOTPROTOnoneIPADDRxxx.xxx.x.xxx#例如:IP…

node seneca_使用Node.js和Seneca编写国际象棋微服务,第2部分

node seneca处理新需求而无需重构 (Handling new requirements without refactoring) Part 1 of this series talked about defining and calling microservices using Seneca. A handful of services were created to return all legal moves of a lone chess piece on a ches…

【OCR技术系列之八】端到端不定长文本识别CRNN代码实现

CRNN是OCR领域非常经典且被广泛使用的识别算法&#xff0c;其理论基础可以参考我上一篇文章&#xff0c;本文将着重讲解CRNN代码实现过程以及识别效果。 数据处理 利用图像处理技术我们手工大批量生成文字图像&#xff0c;一共360万张图像样本&#xff0c;效果如下&#xff1a;…

mysql 修改字段类型死锁_mysql数据库死锁的产生原因及解决办法

数据库和操作系统一样&#xff0c;是一个多用户使用的共享资源。当多个用户并发地存取数据 时&#xff0c;在数据库中就会产生多个事务同时存取同一数据的情况。若对并发操作不加控制就可能会读取和存储不正确的数据&#xff0c;破坏数据库的一致性。加锁是实现数据库并 发控制…

openwrt无盘服务器,搭建基于 OpenWrt/gPXE/iSCSI 的 Windows 无盘工作站

本文要介绍的是如何在 OpenWrt 平台上面搭建无盘工作站服务器以及 Windows 的 iSCSI 部署。当然&#xff0c;由于 OpenWrt 也可以算得上一种 Linux 发行版了&#xff0c;所以本文所介绍的一些方法&#xff0c;在其它 Linux 发行版上面仍有一定的参考价值。整个过程大概分为以下…

Ralink5350开发环境搭建

一、安装虚拟机(Oracle VM VirtualBox 或 VMware Workstation) 二、在虚拟机中安装linux操作系统&#xff08;当前使用的是Ubuntu1204桌面版&#xff09; 三、配置linux相关服务 安装、配置、启动ftp服务apt-get install vsftpd 改动 vsftpd 的配置文件 /etc/vsftpd.conf,将以…

figma下载_Figma重新构想的团队库

figma下载一个新的&#xff0c;功能更强大的界面&#xff0c;用于在整个组织中共享组件 (A new, more powerful interface for sharing Components across your organization) The Team Library in Figma is a set of shared Components across all files in a Team. Component…

boost python导出c++ map_使用Boost生成的Python模块:与C++签名不匹配

我正在使用名为Mitsuba的软件。它附带了一个用Boost包装的Python实现。 Python中的这一行&#xff1a;使用Boost生成的Python模块&#xff1a;与C签名不匹配scene SceneHandler.loadScene(fileResolver.resolve("model.xml"), paramMap)产生一个错误。根据文档&…

CSU-1982 小M的移动硬盘

CSU-1982 小M的移动硬盘 Description 最近小M买了一个移动硬盘来储存自己电脑里不常用的文件。但是他把这些文件一股脑丢进移动硬盘后&#xff0c;觉得这些文件似乎没有被很好地归类&#xff0c;这样以后找起来岂不是会非常麻烦&#xff1f; 小M最终决定要把这些文件好好归类&a…

杜比服务器系统安装教程,win10杜比音效如何安装?win10安装杜比音效的详细教程...

杜比音效想必大家都不陌生&#xff0c;听歌或者看电影开启杜比音效可以给人一种身临其境的感觉。不少朋友都升级了win10系统却不知道如何安装杜比音效&#xff1f;如何为自己的系统安装杜比音效呢&#xff1f;感兴趣的小伙伴请看下面的操作步骤。win10安装杜比音效的方法&#…

剑指Offer_52_正则表达式匹配

题目描述 请实现一个函数用来匹配包括.和的正则表达式。模式中的字符.表示任意一个字符&#xff0c;而表示它前面的字符可以出现任意次&#xff08;包含0次&#xff09;。 在本题中&#xff0c;匹配是指字符串的所有字符匹配整个模式。例如&#xff0c;字符串"aaa"与…

分布式系统开发注意点_分布式系统注意事项

分布式系统开发注意点by Shubheksha通过Shubheksha 分布式计算概述&#xff1a;分布式系统如何工作 (Distributed Computing in a nutshell: How distributed systems work) This post distills the material presented in the paper titled “A Note on Distributed Systems”…

前端if else_应该记录的一些项目代码(前端)

1.共享登录&#xff08;单点登录&#xff09;主要是前端部分主要是根据是否有cookie来判断是否已经登录主系统&#xff0c;然后再根据是否有当前系统的登录信息来&#xff08;这块主要是sessionStorage做的&#xff09;判断是否要再登录当前系统。设置、读取和设置cookie的方法…

Mac端解决(含修改8.0.13版的密码):Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)...

1. 安装mysql但是从来没启动过&#xff0c;今天一启动就报错&#xff1a; Cant connect to local MySQL server through socket /tmp/mysql.sock (2) 其实是mysql服务没起来。。。 localhost:~ miaoying$ mysql.server start Starting MySQL ... SUCCESS! 然后再去sudo mysql就…

塔塔建网站服务器,塔塔帝国忘记哪个区怎么办

7条解答1.在哪个区玩战舰帝国忘记了怎么办?忘了的话可以去官网登陆看看自己的 充值 或者礼包记录 有没有对应的区服 或者电话联系问问客服 通过账号 角色名字来查询2.我忘记在哪个区怎么找如果你有游戏人生资格的话&#xff0c;就很容易找了&#xff0c;在游戏人生的个人主页里…

Ixia推出首款太比特级网络安全测试平台

2016年11月18日&#xff0c;Ixia宣布推出全新CloudStorm平台。作为首款太比特级网络安全测试平台&#xff0c;该平台拥有前所未有的非凡性能&#xff0c;可用于测试及验证超大规模云数据中心不断扩大的容量、效率以及弹性。 ▲Ixia CloudStorm安全测试平台 CloudStorm的正式面市…

[转]oracle分析函数Rank, Dense_rank, row_number

oracle分析函数Rank, Dense_rank, row_number 分析函数2(Rank, Dense_rank, row_number) 目录1.使用rownum为记录排名2.使用分析函数来为记录排名3.使用分析函数为记录进行分组排名一、使用rownum为记录排名&#xff1a; 在前面一篇《Oracle开发专题之&#xff1a;分析函数》&a…