`
universsky
  • 浏览: 92322 次
文章分类
社区版块
存档分类
最新评论

20分钟体验Ruby : Ruby in Twenty Minutes

 
阅读更多
20分钟体验Ruby : Ruby in Twenty Minutes
Introduction
This is a small Ruby tutorial that should take no more than 20 minutes to complete. It makes the assumption that you already have Ruby installed. (If you don’t have Ruby on your computer download and install it before you get started.)
Interactive Ruby
Ruby comes with a program that will show the results of any Ruby statements you feed it. Playing with Ruby code in interactive sessions like this is a terrific way to learn the language.
Open up IRB (which stands for Interactive Ruby).
•If you’re using Mac OS X open up Terminal and type irb, then hit enter.
•If you’re using Linux, open up a shell and type irb and hit enter.
•If you’re using Windows, open fxri from the Ruby section of your Start Menu.
irb(main):001:0>
Ok, so it’s open. Now what?
Type this: "Hello World"
irb(main):001:0> "Hello World"
=> "Hello World"
Ruby Obeyed You!
What just happened? Did we just write the world’s shortest “Hello World” program? Not exactly. The second line is just IRB’s way of telling us the result of the last expression it evaluated. If we want to print out “Hello World” we need a bit more:
irb(main):002:0> puts "Hello World"
Hello World
=> nil
puts is the basic command to print something out in Ruby. But then what’s the => nil bit? That’s the result of the expression. puts always returns nil, which is Ruby’s absolutely-positively-nothing value.
Your Free Calculator is Here
Already, we have enough to use IRB as a basic calculator:
irb(main):003:0> 3+2
=> 5
Three plus two. Easy enough. What about three times two? You could type it in, it’s short enough, but you may also be able to go up and change what you just entered. Try hitting the up-arrow on your keyboard and see if it brings up the line with 3+2 on it. If it does, you can use the left arrow key to move just after the + sign and then use backspace to change it to a * sign.
irb(main):004:0> 3*2
=> 6
Next, let’s try three squared:
irb(main):005:0> 3**2
=> 9
In Ruby ** is the way you say “to the power of”. But what if you want to go the other way and find the square root of something?
irb(main):006:0> Math.sqrt(9)
=> 3.0
Ok, wait, what was that last one? If you guessed, “it was figuring out the square root of nine,” you’re right. But let’s take a closer look at things. First of all, what’s Math?
Modules Group Code by Topic
Math is a built-in module for mathematics. Modules serve two roles in Ruby. This shows one role: grouping similar methods together under a familiar name. Math also contains methods like sin() and tan().
Next is a dot. What does the dot do? The dot is how you identify the receiver of a message. What’s the message? In this case it’s sqrt(9), which means call the method sqrt, shorthand for “square root” with the parameter of 9.
The result of this method call is the value 3.0. You might notice it’s not just 3. That’s because most of the time the square root of a number won’t be an integer, so the method always returns a floating-point number.
What if we want to remember the result of some of this math? Assign the result to a variable.
irb(main):007:0> a = 3 ** 2
=> 9
irb(main):008:0> b = 4 ** 2
=> 16
irb(main):009:0> Math.sqrt(a+b) => 5.0
As great as this is for a calculator, we’re getting away from the traditional Hello World message that beginning tutorials are supposed to focus on… so let’s go back to that.
What if we want to say “Hello” a lot without getting our fingers all tired? We need to define a method!
irb(main):010:0> def h
irb(main):011:1> puts "Hello World!"
irb(main):012:1> end
=> nil
The code def h starts the definition of the method. It tells Ruby that we’re defining a method, that its name is h. The next line is the body of the method, the same line we saw earlier: puts "Hello World". Finally, the last line end tells Ruby we’re done defining the method. Ruby’s response => nil tells us that it knows we’re done defining the method.
The Brief, Repetitive Lives of a Method
Now let’s try running that method a few times:
irb(main):013:0> h
Hello World!
=> nil
irb(main):014:0> h()
Hello World!
=> nil
Well, that was easy. Calling a method in Ruby is as easy as just mentioning its name to Ruby. If the method doesn’t take parameters that’s all you need. You can add empty parentheses if you’d like, but they’re not needed.
What if we want to say hello to one person, and not the whole world? Just redefine h to take a name as a parameter.
irb(main):015:0> def h(name)
irb(main):016:1> puts "Hello #{name}!"
irb(main):017:1> end
=> nil
irb(main):018:0> h("Matz")
Hello Matz!
=> nil
So it works… but let’s take a second to see what’s going on here.
Holding Spots in a String
What’s the #{name} bit? That’s Ruby’s way of inserting something into a string. The bit between the braces is turned into a string (if it isn’t one already) and then substituted into the outer string at that point. You can also use this to make sure that someone’s name is properly capitalized:
irb(main):019:0> def h(name = "World")
irb(main):020:1> puts "Hello #{name.capitalize}!"
irb(main):021:1> end
=> nil
irb(main):022:0> h "chris"
Hello Chris!
=> nil
irb(main):023:0> h
Hello World!
=> nil
A couple of other tricks to spot here. One is that we’re calling the method without parentheses again. If it’s obvious what you’re doing, the parentheses are optional. The other trick is the default parameter World. What this is saying is “If the name isn’t supplied, use the default name of "World"”.
Evolving Into a Greeter
What if we want a real greeter around, one that remembers your name and welcomes you and treats you always with respect. You might want to use an object for that. Let’s create a “Greeter” class.
irb(main):024:0> class Greeter
irb(main):025:1> def initialize(name = "World")
irb(main):026:2> @name = name
irb(main):027:2> end
irb(main):028:1> def say_hi
irb(main):029:2> puts "Hi #{@name}!"
irb(main):030:2> end
irb(main):031:1> def say_bye
irb(main):032:2> puts "Bye #{@name}, come back soon."
irb(main):033:2> end
irb(main):034:1> end
=> nil
The new keyword here is class. This defines a new class called Greeter and a bunch of methods for that class. Also notice @name. This is an instance variable, and is available to all the methods of the class. As you can see it’s used by say_hi and say_bye.
So how do we get this Greeter class set in motion? Create an object.
Now let’s create a greeter object and use it:
irb(main):035:0> g = Greeter.new("Pat")
=> #<Greeter:0x16cac @name="Pat">
irb(main):036:0> g.say_hi
Hi Pat!
=> nil
irb(main):037:0> g.say_bye
Bye Pat, come back soon.
=> nil
Once the g object is created, it remembers that the name is Pat. Hmm, what if we want to get at the name directly?
irb(main):038:0> g.@name
SyntaxError: compile error
(irb):52: syntax error
from (irb):52
Nope, can’t do it.
Under the Object’s Skin
Instance variables are hidden away inside the object. They’re not terribly hidden, you see them whenever you inspect the object, and there are other ways of accessing them, but Ruby uses the good object-oriented approach of keeping data sort-of hidden away.
So what methods do exist for Greeter objects?
irb(main):039:0> Greeter.instance_methods
=> ["method", "send", "object_id", "singleton_methods",
"__send__", "equal?", "taint", "frozen?",
"instance_variable_get", "kind_of?", "to_a",
"instance_eval", "type", "protected_methods", "extend",
"eql?", "display", "instance_variable_set", "hash",
"is_a?", "to_s", "class", "tainted?", "private_methods",
"untaint", "say_hi", "id", "inspect", "==", "===",
"clone", "public_methods", "respond_to?", "freeze",
"say_bye", "__id__", "=~", "methods", "nil?", "dup",
"instance_variables", "instance_of?"]
Whoa. That’s a lot of methods. We only defined two methods. What’s going on here? Well this is all of the methods for Greeter objects, a complete list, including ones defined by ancestor classes. If we want to just list methods defined for Greeter we can tell it to not include ancestors by passing it the parameter false, meaning we don’t want methods defined by ancestors.
irb(main):040:0> Greeter.instance_methods(false)
=> ["say_bye", "say_hi"]
Ah, that’s more like it. So let’s see which methods our greeter object responds to:
irb(main):041:0> g.respond_to?("name")
=> false
irb(main):042:0> g.respond_to?("say_hi")
=> true
irb(main):043:0> g.respond_to?("to_s")
=> true
So, it knows say_hi, and to_s (meaning convert something to a string, a method that’s defined by default for every object), but it doesn’t know name.
Altering Classes—It’s Never Too Late
But what if you want to be able to view or change the name? Ruby provides an easy way of providing access to an object’s variables.
irb(main):044:0> class Greeter
irb(main):045:1> attr_accessor :name
irb(main):046:1> end
=> nil
In Ruby, you can open a class up again and modify it. The changes will be present in any new objects you create and even available in existing objects of that class. So, let’s create a new object and play with its @name property.
irb(main):047:0> g = Greeter.new("Andy")
=> #<Greeter:0x3c9b0 @name="Andy">
irb(main):048:0> g.respond_to?("name")
=> true
irb(main):049:0> g.respond_to?("name=")
=> true
irb(main):050:0> g.say_hi
Hi Andy!
=> nil
irb(main):051:0> g.name="Betty"
=> "Betty"
irb(main):052:0> g
=> #<Greeter:0x3c9b0 @name="Betty">
irb(main):053:0> g.name
=> "Betty"
irb(main):054:0> g.say_hi
Hi Betty!
=> nil
Using attr_accessor defined two new methods for us, name to get the value, and name= to set it.
Greeting Anything and Everything, MegaGreeter Neglects None!
This greeter isn’t all that interesting though, it can only deal with one person at a time. What if we had some kind of MegaGreeter that could either greet the world, one person, or a whole list of people?
Let’s write this one in a file instead of directly in the interactive Ruby interpreter IRB.
To quit IRB, type “quit”, “exit” or just hit Control-D.
#!/usr/bin/env ruby
class MegaGreeter
attr_accessor :names
# Create the object
def initialize(names = "World")
@names = names
end
# Say hi to everybody
def say_hi
if @names.nil?
puts "..."
elsif @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
# Say bye to everybody
def say_bye
if @names.nil?
puts "..."
elsif @names.respond_to?("join")
# Join the list elements with commas
puts "Goodbye #{@names.join(", ")}. Come back soon!"
else
puts "Goodbye #{@names}. Come back soon!"
end
end
end
if __FILE__ == $0
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
# Change name to be "Zeke"
mg.names = "Zeke"
mg.say_hi
mg.say_bye
# Change the name to an array of names
mg.names = ["Albert", "Brenda", "Charles",
"Dave", "Engelbert"]
mg.say_hi
mg.say_bye
# Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
end
Save this file as “ri20min.rb”, and run it as “ruby ri20min.rb”. The output should be:
Hello World!
Goodbye World. Come back soon!
Hello Zeke!
Goodbye Zeke. Come back soon!
Hello Albert!
Hello Brenda!
Hello Charles!
Hello Dave!
Hello Engelbert!
Goodbye Albert, Brenda, Charles, Dave, Engelbert. Come
back soon!
...
...
There are a lot of new things thrown into this final example that we can take a deeper look at.
So, looking deeper at our new program, notice the initial lines, which begin with a hash mark (#). In Ruby, anything on a line after a hash mark is a comment and is ignored by the interpreter. The first line of the file is a special case, and under a Unix-like operating system tells the shell how to run the file. The rest of the comments are there just for clarity.
Our say_hi method has become a bit trickier:
# Say hi to everybody
def say_hi
if @names.nil?
puts "..."
elsif @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
It now looks at the @names instance variable to make decisions. If it’s nil, it just prints out three dots. No point greeting nobody, right?
Cycling and Looping—a.k.a. Iteration
If the @names object responds to each, it is something that you can iterate over, so iterate over it and greet each person in turn. Finally, if @names is anything else, just let it get turned into a string automatically and do the default greeting.
Let’s look at that iterator in more depth:
@names.each do |name|
puts "Hello #{name}!"
end
each is a method that accepts a block of code then runs that block of code for every element in a list, and the bit between do and end is just such a block. A block is like an anonymous function or lambda. The variable between pipe characters is the parameter for this block.
What happens here is that for every entry in a list, name is bound to that list element, and then the expression puts "Hello #{name}!" is run with that name.
Most other programming languages handle going over a list using the for loop, which in C looks something like:
for (i=0; i<number_of_elements; i++)
{
do_something_with(element[i]);
}
This works, but isn’t very elegant. You need a throw-away variable like i, have to figure out how long the list is, and have to explain how to walk over the list. The Ruby way is much more elegant, all the housekeeping details are hidden within the each method, all you need to do is to tell it what to do with each element. Internally, the each method will essentially call yield "Albert", then yield "Brenda" and then yield "Charles", and so on.
Blocks, the Highly Sparkling Glint on the Edge of Ruby
The real power of blocks is when dealing with things that are more complicated than lists. Beyond handling simple housekeeping details within the method, you can also handle setup, teardown, and errors—all hidden away from the cares of the user.
# Say bye to everybody
def say_bye
if @names.nil?
puts "..."
elsif @names.respond_to?("join")
# Join the list elements with commas
puts "Goodbye #{@names.join(", ")}. Come back soon!"
else
puts "Goodbye #{@names}. Come back soon!"
end
end
The say_bye method doesn’t use each, instead it checks to see if @names responds to the join method, and if so, uses it. Otherwise, it just prints out the variable as a string. This method of not caring about the actual type of a variable, just relying on what methods it supports is known as “Duck Typing”, as in “if it walks like a duck and quacks like a duck…”. The benefit of this is that it doesn’t unnecessarily restrict the types of variables that are supported. If someone comes up with a new kind of list class, as long as it implements the join method with the same semantics as other lists, everything will work as planned.
Kicking Off the Script
So, that’s the MegaGreeter class, the rest of the file just calls methods on that class. There’s one final trick to notice, and that’s the line:
if __FILE__ == $0
__FILE__ is the magic variable that contains the name of the current file. $0 is the name of the file used to start the program. This check says “If this is the main file being used…” This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.
Consider Yourself Introduced
So that’s it for the quick tour of Ruby. There’s a lot more to explore, the different control structures that Ruby offers; the use of blocks and yield; modules as mixins; and more. I hope this taste of Ruby has left you wanting to learn more.
If so, please head on over to our Documentation area, which rounds up links to manuals and tutorials, all freely available online.
Or, if you’d really like to dig into a book, check the book list (off-site link) for titles available for sale online or at your local bookseller.
20分钟体验Ruby

介绍
这是一个小的Ruby教程,应采取不超过20分钟就可以完成。它使假设你已经安装Ruby。 (如果你没有红宝石您的计算机上下载并安装它,在你开始之前。)



打开IRB(交互式Ruby)。

•如果您使用的是Mac OS X打开终端并输入irb,然后按下回车键。
•如果您使用的是Linux,打开一个shell类型的IRB和命中进入。
•如果您使用的是Windows,开放fxri从开始菜单Ruby的部分。

刚刚发生了什么?难道我们只是写出世界上最短的“Hello World”程序?不完全是。第二行是刚刚IRB的方式告诉我们它评估的最后一个表达式的结果。如果我们要打印出“Hello World”的,我们需要多一点:

IRB(主):002:0>提出的“Hello World”
的Hello World
=>零
把基本的命令打印出来的东西在Ruby。那么是什么=>零位?这就是表达式的结果。把总是返回nil,这是Ruby的绝对正没什么价值。

这里是你的免费计算器
目前,我们有足够的使用内部评级法作为一项基本的计算器:

IRB(主):003:0> 3 +2
=> 5
三加二。很容易做到。约三倍两个?你可以键入它,它是足够短,但你也许还可以去改变你刚才输入。试着打键盘上的向上箭头,看它是否符合3 +2。如果是这样,你可以使用左箭头键来移动“+”号后,然后用退格键,将其更改为一个*符号。

IRB(主):004:0> 3 * 2
=> 6
接下来,让我们尝试三个平方:

IRB(主):005:0> 3的** 2
=> 9
在Ruby中**的方式,你说“给力”。但是,如果你希望走另一条路,找到的平方根的东西吗?

IRB(主):006:0>的Math.sqrt(9)
=> 3.0
好,等我,是最后一个?如果你猜到了,“它是搞清楚9的平方根,”你说得对。但是,让我们来仔细看看事情。首先,什么是数学?

主题模块组代码
数学是一个内置的数学模块。模块用于在Ruby中的两个角色。这显示了一个角色:一个熟悉的名字下一起类似的方法进行分组。

接下来是一个点。点做什么?点是你如何识别接收的消息。什么消息?在这种情况下,它是SQRT(9),这意味着调用该方法SQRT,速记“平方根”9的参数。

此方法调用的结果是3.0的值。您可能会注意到它不只是3。这是因为大部分时间的平方根数字将不会是一个整数,因此该方法总是返回一个浮点数。

如果我们要记住一些数学的结果是什么?结果分配给一个变​​量。

IRB(主):007:0> = 3 ** 2
=> 9
IRB(主):008:0> B = 4 ** 2
=> 16
IRB(主):009:0>的Math.sqrt(A + B)=> 5.0
一样大,这是一个计算器,我们越来越远离了传统的Hello World消息开始教程应该把重点放在...让我们回到那个。


如果我们想要说“你好”了很多,没有得到我们的手指都累吗?我们需要定义一个方法!

IRB(主):010:0> DEFħ
IRB(主):011:1>提出的“Hello World!”
IRB(主):012:1>结束
=>零
码高清H开始的方法的定义中。它告诉红宝石,我们定义了一个方法,其名称为h。下一行是身体的方法,我们前面看到的:在同一行提出的“Hello World”。最后,最后一行结束红宝石告诉我们定义的方法来完成。 Ruby的响应=>零告诉我们,它知道我们所做的定义方法。

简短,重复住的方法
现在,让我们尝试几次运行的方法:

IRB(主):013:0> H
世界您好!
=>零
IRB(主):014:0>小时()
世界您好!
=>零
嗯,这是很容易的。在Ruby中调用一个方法是红宝石只是提它的名字一样容易。如果该方法不带参数,所有你需要的。您可以添加空括号,如果你想,但他们并不需要。

如果我们想要一个人,而不是整个世界问好是什么?只需重新定义h来取了个名字作为参数。

IRB(主):015:0> DEF h(名称)
IRB(主):016:1>把“您好#{name}的!”
IRB(主):017:1>结束
=>零
IRB(主):018:0>h(“马茨”)
您好马茨!
=>零

所以它的工作原理......但让我们花一秒钟,看到这里发生了什么事情。


#{name}的位是什么?这是Ruby的方式插入到一个字符串的东西。在大括号之间的位被转换为一个字符串(如果没有的话),并代入在该点的外字符串。您还可以使用,以确保某人的名字是正确的大写:

IRB(主):019:0> DEF H(名称=“世界”)
IRB(主):020:1>提出“,你好#{name.capitalize}!”
IRB(主):021:1>结束
=>零
IRB(主):022:0> H“克里斯”
你好,克里斯!
=>零
IRB(主):023:0> H
世界您好!
=>零
其他招数一对夫妇在这里发现。其一是我们没有括号再次调用该方法。如果很明显,你在做什么,括号中是可选的。另一个诀窍是世界的默认参数。这说的是“如果不提供的名称,使用默认的名称”世界“。

演变成一个迎宾
如果我们想要一个真正的招待员左右,记住你的名字,欢迎您的光临,并尊重对待你总是什么。您可能要使用对象。让我们创建一个“迎宾”类。

IRB(主):024:0>类迎宾
IRB(主):025:1> DEF初始化(名称=“世界”)
IRB(主):026:2> @名称=名称
IRB(主):027:2>结束
IRB(主):028:1> DEF say_hi
IRB(主):029:2>把“嗨#{@名}!”
IRB(主):030:2>结束
IRB(主):031:1> DEF say_bye
IRB(主):032:2>把“再见#{@名},很快回来。”
IRB(主):033:2>结束
IRB(主):034:1>结束
=>零
这里新的关键字是class。这定义了一个新的称为迎宾类,这个类的方法和一堆。同时注意到@名。这是一个实例变量,并且是可用的类的所有方法。正如你可以看到它的使用由say_hi say_bye。

那么,我们如何得到这个Greeter类集运动?创建一个对象。


现在,让我们创建一个招待员的对象,并使用它:

IRB(主):035:0> G = Greeter.new(“八”)
=>#<Greeter:0x16cac @name="Pat">的
IRB(主):036:0> g.say_hi“
嗨专利!
=>零
IRB(主):037:0> g.say_bye“
细则八,很快回来。
=>零
克对象被创建后,它会记住这个名字是帕特。嗯,如果我们想获得直接的名字?

IRB(主):038:0> G @名
语法错误:编译错误
(IRB):52:语法错误
(IRB):52
不,不能这样做。

根据对象的皮肤
实例变量里面隐藏的对象。他们不是可怕的隐藏,你看到他们每当您检查对象,并有其他的方式访问它们,但,Ruby使用良好的面向对象的方法,保持数据排序藏起来。



IRB(主):039:0> Greeter.instance_methods的
=> [“方法”,“送”,“OBJECT_ID”中,“singleton_methods”
“__send__”,“平等”,“污点”,“冻结?”
的“instance_variable_get”,“kind_of?”,“to_a”
instance_eval的“,”类型“,”protected_methods“,”延长“
“互不干涉”,“显示器”,“instance_variable_set”,“哈希”的,
“用is_a?”,“的to_s”,“阶级”,“污点”,“private_methods”
的untaint,的“say_hi”的“id”,“检查”,“==”,“===”,
“克隆”,“public_methods”,“respond_to方法吗?”,“冻结”,
“say_bye”,“__id__”,“=”,“方法”,“无”,“DUP”
“instance_variables”,“instance_of?]
哇。这是一个很大的方法。我们只定义了两种方法。这是怎么回事呢?嗯,这是迎宾对象,一个完整的列表,包括那些由祖先类定义的所有方法。如果我们要列出迎宾定义的方法,我们可以告诉它不包括祖先传递给它的参数假的,这意味着我们不希望祖先所定义的方法。

IRB(主):040:0> Greeter.instance_methods(假)
=> [的“say_bye”,“say_hi”]
啊,那是更喜欢它。所以,让我们来看看我们的招待员对象响应方法:

IRB(主):041:0> g.respond_to(“名称”)?
=>假
IRB(主):042:0> g.respond_to?(“say_hi”)
=>真
IRB(主):043:0> g.respond_to?(“的to_s”的)
=>真
因此,它知道say_hi的,的to_s(即转换为字符串,默认情况下,每个对象的定义的方法),但它不知道名称。

改变类它永远不会太晚
但是如果你想能够查看或更改名称? Ruby提供了一种简单的方法,访问对象的变量。

IRB(主):044:0>类迎宾
IRB(主):045:1> attr_accessor中:名称
IRB(主):046:1>结束
=>零
在Ruby中,你可以打开一个类,再进行修改。这些变化将出现在任何新创建的对象,甚至可以在现有的那个类的对象。所以,让我们创建一个新的对象,并发挥其@ name属性。

IRB(主):047:0> G = Greeter.new(“安迪”)
=>#<Greeter:0x3c9b0 @name="Andy">
IRB(主):048:0> g.respond_to(“名称”)?
=>真
IRB(主):049:0> g.respond_to?(“=”)
=>真
IRB(主):050:0> g.say_hi“
嗨,安迪!
=>零
IRB(主):051:0> g.name =“贝蒂”
=>“贝蒂”
IRB(主):052:0> G
=>#<Greeter:0x3c9b0 @name="Betty">
IRB(主):053:0> g.name“
=>“贝蒂”
IRB(主):054:0> g.say_hi“
嗨,贝蒂!
=>零
attr_accessor中为我们定义了两个新的方法,名称的值,名称=来设置它。

贺卡任何事情,一切中,MegaGreeter忽视没有了!
此招待员是不是所有的有趣,但它只能处理一个人在同一时间。如果我们有某种MegaGreeter既可以迎接世界,一个人或整个名单的人吗?

让我们写这个文件,而不是直接在交互式Ruby解释器IRB。

要退出的IRB,键入“跳槽”,“退出”,或者只是打控制-D。

#!的/ usr / bin中/ env的红宝石

类MegaGreeter
attr_accessor中:名称

#创建对象
DEF初始化(名称=“世界”)
@名称=名称
结束

#给大家打个招呼
DEF say_hi
if@names.nil?
把“...”
elsif@names.respond_to(“每个”?)

#@名称是某种类型的列表,迭代!
@ names.each |名称|
把“您好#{name}!”
结束
其他
把“您好#{@名}!”
结束
结束

#大家说再见
DEF say_bye
if@names.nil?
把“...”
elsif@names.respond_to(“加入”)?
加入列表中的元素用逗号
把“再见#{@ names.join(”,“)}。很快回来!”
其他
把“再见#{@名},很快回来!”
结束
结束

结束


如果__ FILE__ == $ 0
毫克= MegaGreeter.new
mg.say_hi
mg.say_bye

#更改名称是“齐克”
mg.names =“齐克”
mg.say_hi
mg.say_bye

#将名称更改为一个数组名称
mg.names = [“伟业”,“布兰达”,“查尔斯”,
“戴夫”,“恩格尔贝特”]
mg.say_hi
mg.say_bye

#更改为零
mg.names =零
mg.say_hi
mg.say_bye
结束
保存此文件为“ri20min.rb”的,和运行它为“红宝石ri20min.rb”。输出应该是:

世界您好!
再见世界。很快回来!
您好泽科!
再见泽科。很快回来!
您好伟业!
布伦达您好!
查尔斯·您好!
戴夫你好!
您好恩格尔贝特!
再见伟业,布伦达,查尔斯,戴夫,恩格尔贝特。来
马上回来!
...
...
现在有很多新的东西扔进这最后一个例子,我们可以更深入地了解。


因此,在我们的新节目寻找更深,注意到初始线,开始与一个hash符号(#)。在Ruby中,任何一个哈希标记上线后是注释,被忽略的解释。该文件的第一行是一种特殊的情况,并告诉shell类似Unix的操作系统下如何运行文件。其余的意见只是为了清晰。

我们的say_hi法已经变得有点棘手:

#给大家打个招呼
DEF say_hi
if@names.nil?
把“...”
elsif@names.respond_to(“每个”?)
#@名称是某种类型的列表,迭代!
@ names.each |名称|
把“您好#{name}!”
结束
其他
把“您好#{@名}!”
结束
结束
现在看起来@名实例变量作出决定。如果它是零,它只是打印出三个点。没有点问候没人管,对不对?

自行车循环a.k.a。迭代
如果@名对象响应每个,它的东西,你可以遍历,所以遍历它,迎接每个人。最后@名称,如果是别的,只是让它变成一个字符串自动做默认的问候语。

让我们来看看更深入,迭代:

@ names.each |名称|
把“您好#{name}!”
结束
每一个方法,它接受一个代码块在一个列表中的每个元素,然后运行代码块之间的位做和结束就是这样一个块。块是像一个匿名函数或lambda。管道字符之间的变量是用于此功能块的参数。

这里发生了什么,列表中的每个条目,名称绑定列表元素,并表达将“您好#{name}的!”运行使用该名称。

大多数其他编程语言处理使用的循环,这在C看起来像一个列表:

(= 0; <number_of_elements; + +)
{
map里(元素[]);
}
这工作,但不是很优雅。你需要一个像我扔掉的变量,要搞清楚多久列表,并解释如何走在列表。红宝石的方式更优雅,所有的看家细节隐藏在每一个方法,所有你需要做的就是告诉它做什么用的每个元素。内部,基本上每个方法调用yield“伟业”,然后产生“布兰达”,然后产生“查尔斯”,等等。

块,高闪闪发光的红宝石的边缘闪烁
的真正威力块处理比列表更复杂的东西,是时。除了处理简单的看家细节,在该方法中,你也可以处理设置,拆除和错误都藏身从用户的关心。

#大家说再见
DEF say_bye
if@names.nil?
把“...”
elsif@names.respond_to(“加入”)?
加入列表中的元素用逗号
把“再见#{@ names.join(”,“)}。很快回来!”
其他
把“再见#{@名},很快回来!”
结束
结束
不使用的say_bye方法,而不是它会检查,如果某个名字的连接的方法的反应,如果是这样,使用它。否则,它只是打印出来作为一个字符串变量。这种方法不关心变量的实际类型,仅仅依靠它支持什么方法被称为“鸭打字”,“如果它走起来像鸭子,叫起来像鸭子......”。这样做的好处是,它并没有不必要地限制所支持的变量的类型。如果有人想出了一种新的列表类,只要它实现了与其他列表相同的语义的连接方法,一切都会按计划工作。

开球脚本
所以,这是的MegaGreeter类的文件,剩下的只是调用该类的方法。还有最后一个绝招需要注意的,那就是行:

如果__ FILE__ == $ 0
__FILE__包含当前文件的名称是神奇的变量。 $ 0是用于启动程序的文件的名称。此检查说:“如果这是主要的文件正在使用......”这允许一个文件被用作图书馆,在这种情况下不执行代码,但如果该文件是被用来作为一个可执行文件,然后执行该代码。

认为自己介绍
所以这是它的快速游览的Ruby。有很多更多的探索,红宝石提供不同的控制结构;使用块和产量;模块混入;多。我希望,红宝石这个味道已经离开你想了解更多信息。

如果是这样,请头到我们的文档区域,这轮手册及教程的链接,全部可在网上免费。

或者,如果你真的想挖成书,查书列表(异地链接)提供在线销售的标题,或您当地的书商。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics