这篇的内容很简单, 基本上都是以前用过的语法, 稍微讲的详细一点.
1. if .. then .. else
#!/opt/ruby/bin/ruby
def get_daytype(aDay)
if (aDay.to_s.downcase == 'saturday') || (aDay.to_s.downcase == 'sunday') # 分行写的话then可以忽略.
daytype = 'weekend'
else
daytype = 'weekday'
end
return daytype
end
print ("please enter day:")
aDay = gets().chomp
puts( get_daytype(aDay) )
一个等号赋值, 两个等号为相等. 三个等号后面讲.
执行结果 :
please enter day:sunday
weekend
if .. else .. end还有一种简写.( ? .. : )
例如以下两句是一样的 :
('abc' == 'abc') ? puts("true") : puts("false")
if ('abc' == 'abc') then puts("true") else puts("false") end
? .. : 也可以写成多行, 只不过有一些特殊的限制 :
?结尾行下面必须是 :结尾的行 .
2. and, or, not ( && , || , ! )
and , or , not 的另一种表示方法是, && , || , !
因为两者的优先级不一样,
一般不要混用, 建议要么全部使用and, or , not. 或全部使用 &&, ||, ! .
另外需要注意的是, 使用括弧会使得逻辑更明了.
3. if .. elsif
前面讲的是单个条件的判断, 如果有多个条件的话就要用到elsif. 例如 :
4. unless
#!/opt/ruby/bin/ruby
loop do
print("Please enter a number or (q to exit):")
input = gets().chomp
if input == 'q'
puts( "Bye" )
break
elsif input.to_i > 800 && input.to_i <= 1000
puts( "That's a high rate of pay!" )
elsif input.to_i <= 800 && input.to_i > 0
puts( "We can afford that" )
else
puts( "I said: Enter a number between 1 and 1000!" )
end
end
4. unless
类似while 和until是对立的. if和unless也是对立的.
unless () 等同于 if !()
5. if and unless Modifiers
if !(1==1) then
puts("ture")
else
puts("false")
end
unless 1==1 then
puts("ture")
else
puts("false")
end
5. if and unless Modifiers
类似while, until的modifier写法, if和unless也有类似写法.但是if和unless的modifier写法不会有one or more times的执行次数. 也就是必须是先判断再执行的.
6. case
puts("true") if (1==1)
puts("true") unless !(1==1)
begin
puts("true") # 不执行
puts("true again") # 不执行
end if (1!=1)
begin
puts("true") # 不执行
puts("true again") # 不执行
end unless !(1!=1)
6. case
当有多个条件判断时, 写if .. elsif .. elsif .. 可能会觉得繁琐. 可以用case替代.
执行结果 :
case中的Range运用 :
case 也是从上往下匹配的, 匹配到之后后面的将不再进行匹配 :
case的返回值赋值给其他变量 :
执行结果 :
7. CONSTANTS
case (变量, 或算数运算表达式等)
when ? then
表达式
when ? then
表达式
...
else
表达式
end
#!/opt/ruby/bin/ruby
loop do
print("Please enter a number or (q to exit):")
i = gets().chomp
case( i )
when '1' then puts("It's Monday" )
when '2' then puts("It's Tuesday" )
when '3' then puts("It's Wednesday" )
when '4' then puts("It's Thursday" )
when '5' then puts("It's Friday" )
when ('6'..'7') then puts( "Yippee! It's the weekend! " )
when 'q' then puts("Bye")
break
else puts( "That's not a real day!" )
end
end
执行结果 :
./test.rb
Please enter a number or (q to exit):1
It's Monday
Please enter a number or (q to exit):2
It's Tuesday
Please enter a number or (q to exit):3
It's Wednesday
Please enter a number or (q to exit):4
It's Thursday
Please enter a number or (q to exit):5
It's Friday
Please enter a number or (q to exit):6
Yippee! It's the weekend!
Please enter a number or (q to exit):7
Yippee! It's the weekend!
Please enter a number or (q to exit):8
That's not a real day!
Please enter a number or (q to exit):q
Bye
case中的Range运用 :
def method1(i)
case (i)
when ('a'..'z'), ('A'..'Z'), ('0'..'1') then
puts("it's a letter")
when (0..9) then
puts("it's a number")
else
puts("please enter one character a time")
end
end
method1('1')
method1(1)
method1('z')
method1('A')
method1('abc')
# 执行结果 :
it's a letter
it's a number
it's a letter
it's a letter
please enter one character a time
case 也是从上往下匹配的, 匹配到之后后面的将不再进行匹配 :
case( i )
when 1 then puts("It's Monday" )
when 2 then puts("It's Tuesday" )
when 3 then puts("It's Wednesday" )
when 4 then puts("It's Thursday" )
when 5 then puts("It's Friday" )
puts("...nearly the weekend!")
when 6, 7
puts("It's Saturday!" ) if i == 6
puts("It's Sunday!" ) if i == 7
puts( "Yippee! It's the weekend! " )
# the following never executes, 下面的 when 5 永远都不会执行.
when 5 then puts( "It's Friday all over again!" )
else puts( "That's not a real day!" )
end
case的返回值赋值给其他变量 :
def method1(i)
case (i)
when ('a'..'z'), ('A'..'Z'), ('0'..'1') then
puts("it's a letter")
return "letter"
when (0..9) then
puts("it's a number")
return "number"
else
puts("please enter one character a time")
return "nonalphanumeric"
end
end
a = method1('1')
puts(a)
执行结果 :
it's a letter
letter
7. CONSTANTS
常量, 这个在Ruby里面其实不是强制限制不能修改的, 只是语义上面来说不能修改, 当然建议还是不要修改它.
查看有哪些常量, 例如我们看看Object类有哪些常量.
查看常量的值 : 用两个冒号, 其实class中的class也是通过两个冒号来调用的.
print (Object.constants.sort) # 用到constants方法
输出 : (其中包含了类,例如Array, Data等)
[:ARGF, :ARGV, :ArgumentError, :Array, :BasicObject, :Bignum, :Binding, :CROSS_COMPILING, :Class, :Comparable, :Complex, :Config, :Data, :Dir, :ENV, :EOFError, :Encoding, :EncodingError, :Enumerable, :Enumerator, :Errno, :Exception, :FALSE, :FalseClass, :Fiber, :FiberError, :File, :FileTest, :Fixnum, :Float, :FloatDomainError, :GC, :Gem, :Hash, :IO, :IOError, :IndexError, :Integer, :Interrupt, :Kernel, :KeyError, :LoadError, :LocalJumpError, :Marshal, :MatchData, :Math, :Method, :Module, :Mutex, :NIL, :NameError, :NilClass, :NoMemoryError, :NoMethodError, :NotImplementedError, :Numeric, :Object, :ObjectSpace, :Proc, :Process, :RUBY_COPYRIGHT, :RUBY_DESCRIPTION, :RUBY_ENGINE, :RUBY_PATCHLEVEL, :RUBY_PLATFORM, :RUBY_RELEASE_DATE, :RUBY_REVISION, :RUBY_VERSION, :Random, :Range, :RangeError, :Rational, :RbConfig, :Regexp, :RegexpError, :RubyVM, :RuntimeError, :STDERR, :STDIN, :STDOUT, :ScriptError, :SecurityError, :Signal, :SignalException, :StandardError, :StopIteration, :String, :Struct, :Symbol, :SyntaxError, :SystemCallError, :SystemExit, :SystemStackError, :TOPLEVEL_BINDING, :TRUE, :Thread, :ThreadError, :ThreadGroup, :Time, :TrueClass, :TypeError, :UnboundMethod, :ZeroDivisionError]
查看常量的值 : 用两个冒号, 其实class中的class也是通过两个冒号来调用的.
print(Math.constants.sort) # 查看Math class的常量 :
[:DomainError, :E, :PI]
puts(Math::E)
puts(Math::PI)
Math::PI = 100
puts(Math::PI)
输出结果 :
修改PI的时候给出了一个警告, 当然值已经修改了.
8. === method
C:/Users/digoal/Desktop/new.rb:4: warning: already initialized constant PI
2.718281828459045
3.141592653589793
100
8. === method
这个方法比较有意思, Range 类对象的===方法相当于include?的用法 . 而Array类对象的===方法就是相等的意思.
Regexp 类对象的===方法则是匹配的意思, 因此使用===方法时, 左边是它的对象, 右边是传递给这个方法的参数.
输出结果 :
Range的instance method ===相当于 include? . 下面两句得到的结果是一样的
puts(%r/^abc$/.===('abc'))
puts(%r/^abc$/ === 'abc')
puts([1,2,3] === [1,2,3])
puts([1,2,3].===([3,2,1]))
puts((1..10).===(1))
puts((1..10) === 1)
输出结果 :
true
true
true
false
true
true
Range的instance method ===相当于 include? . 下面两句得到的结果是一样的
puts((1..10).include?(1))
puts((1..10) === 1)
9. catch, throw
其他编程语言中有goto可以直接跳转到其他部分, 在Ruby中没有goto的用法. 但是有catch和throw. 类似goto.
catch在一个代码块的外围, 参数是Symbol.
throw在代码块(do end或{} )的里面用于跳出catch包围的代码块. 参数也是Symbol.
例如 :
执行结果 :
#!/opt/ruby/bin/ruby
def dothings( aNum )
i = 0
while true
puts( "I'm doing things..." )
i += 1
throw( :go_for_tea ) if ( i == aNum )
# throws to end of go_to_tea block
end
end
catch( :go_for_tea ) { # this is the :go_for_tea block
dothings(5)
}
catch( :finished ) do
print( 'Enter a number: ' )
num = gets().chomp.to_i
if num == 0 then
throw :finished
end
puts( 100 / num )
catch( :go_for_tea ) {
dothings(5)
}
puts( "Things have all been done. Time for tea!" )
end
执行结果 :
./test.rb
I'm doing things...
I'm doing things...
I'm doing things...
I'm doing things...
I'm doing things...
Enter a number: 100
1
I'm doing things...
I'm doing things...
I'm doing things...
I'm doing things...
I'm doing things...
Things have all been done. Time for tea!
不管是goto还是catch, throw都需要慎重使用.
【参考】
The Book Of Ruby
Ruby 1.9.3 API