孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

可以用{}书写一个block,如  {puts "hello"}

也可以不用{},直接写为puts "hello"

或用

begin

  puts "hello"

end

 

在每一行可以加;

puts "hello";

puts "hey";

 

或不加;

puts "hello"

puts "hey"

 

或在do..end中定义

do

  club.enroll(person)

  person.socialize

end

 

另外

if radiation>3000

  puts "Danger"

end

可写为

puts "Danger" if radiation>3000

 

square=2

while square<1000

  square=square*square

end

 

等同与

square=2

square=square*square while square<1000

 

类似perl,ruby运行并行赋值

a,b=b,a

表示将a与b互换

x=0

a,b,c=x,(x+=1),(x+=1) 得到 [0,1,2]

 

case语句

rating=case votes_cast

    when 0..10   then Rating::SkipThisOne

    when 10..50  then Rating::CouldDoBetter

    else

    end

 

+号的重载

class Fixnum

  alias old_plus +

  def +(other)

    old_plus(other).succ

  end

end

 

1+2 得到 4

a=3

a+=4  得到  8

a+a+a  得到 26

 

注: alias为取别名

 

if 和unless

if和unless互为相反的符号

如if a>2 then puts "s" 可写为 unless a<=2 then puts "s"

 

if a="ddd" then puts "1" puts "2"

else puts "3"

end

可加上then,写为

if a="ddd" then

  puts "1"

elseif a="ttt" then

  puts "2"

else

  puts "3"

end

 

 

 

posted on 2012-03-26 20:45  孤独的猫  阅读(228)  评论(0编辑  收藏  举报