从命令行执行Ruby

通过irb启动Ruby的交互式命令行。

1
2
3
4
5
6
7
8
9
10
11
12
13
>> puts 'hello, world'
hello, world
=> nil
>> language = 'Ruby'
=> "Ruby"
>> puts "hello. #{language}"
hello, Ruby
=> nil
>> language = 'my Ruby'
=> "my Ruby"
>> puts "hello, #{language}"
hello, Ruby
=> nil

一切都是对象

Ruby是一门纯面向对象语言。在本章中你将看到,Ruby是如何深入挖掘面向对象思想的。先来看一些基本对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>> 4
=> 4
>> 4.class
=> Fixnum < Integer
>> 4 + 4
=> 8
>> 8
=> 8
>> 4.methods
=> [
[ 0] !() Fixnum (BasicObject)
[ 1] !=(arg1) Fixnum (BasicObject)
[ 2] !~(arg1) Fixnum (Kernel)
[ 3] %(arg1) Fixnum
[ 4] &(arg1) Fixnum
[ 5] *(arg1) Fixnum
[ 6] **(arg1) Fixnum
[ 7] +(arg1) Fixnum
[ 8] +@() Fixnum (Numeric)
[ 9] -(arg1) Fixnum
[ 10] -@() Fixnum
[ 11] /(arg1) Fixnum
...

true 和 false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>> puts 'This appears to be true.'
This appears to be true.
=> nil
>> puts 'This appears to be true.' if 'random string'
(pry):21: warning: string literal in condition
This appears to be true.
=> nil
>> puts 'This appears to be true.' if 0
This appears to be true.
=> nil
>> puts 'This appears to be true.' if true
This appears to be true.
=> nil
>> puts 'This appears to be true.' if false
=> nil
>> puts 'This appears to be true.' if nil
=> nil
>>

也就是说,除了nil和false之外,其他值都代表true。C和C++程序员可得小心了,0也是true!

逻辑运算符

Ruby的逻辑运算符,跟C、C++、C#、Java差不多,但也稍有不同。

  • and(也可写为&&)是逻辑与,or(也可写为||)是逻辑或。这两种运算符为短路求值运算符:即用这两种运算符验证表达式时,一旦表达式的值已能明确求出,解释器就不再继续执行后面的表达式代码1
  • 如果想执行整个表达式的话,可以用&或|进行比较。

下面,看看它们是如何运行的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>> true and false
=> false
>> true or false
=> true
>> false && false
=> false
>> true && this_will_cause_an_error
NameError: undefined local variable or method `this_will_cause_an_error' for #<IRB::TopLevel:0x00000003ae4838>
from (pry):29:in `__pry__'
>> false && this_will_not_cause_an_error
=> false
>> true || this_will_not_cause_an_error
=> true
>> true or this_will_not_cause_an_error
=> true
>> false || this_will_cause_an_error
NameError: undefined local variable or method `this_will_cause_an_error' for #<IRB::TopLevel:0x00000003ae4838>
from (pry):32:in `__pry__'
>> true | false
=> true

Comments