casewhensong.name=='Misty'puts'Not again!'whensong.duration>120puts'Too long!'whenTime.now.hour>21puts"It's too late"elsesong.playend# another stylekind=caseyearwhen1850..1889then'Blues'when1890..1909then'Ragtime'when1910..1929then'New Orleans Jazz'when1930..1939then'Swing'when1940..1950then'Bebop'else'Jazz'end
# Public: Duplicate some text an arbitrary number of times.## text - The String to be duplicated.# count - The Integer number of times to duplicate the text.## Examples ## multiplex('Tom', 4)# # => 'TomTomTomTom'## Returns the duplicated String.defmultiplex(text,count)text*countend
语法 (Syntax)
当在def方法不接受任何参数的时候省略括号。 当有参数的时候, 使用括号。
1234567
defsome_method# body omittedenddefsome_method_with_arguments(arg1,arg2)# body omittedend
# baddefsome_method(arg1=:default,arg2=nil,arg3=[])# do something...end# gooddefsome_method(arg1=:default,arg2=nil,arg3=[])# do something...end
条件中使用了赋值操作符应该用括号包围。
12345678
# good - shows intented use of assignmentif(v=array.grep(/foo/))...# badifv=array.grep(/foo/)...# also good - shows intended use of assignment and has correct precedence.if(v=self.next_value)=="hello"...
用 ||= 来初始化变量.
12
# set name to Bozhidar, only if it's nil or falsename||='Bozhidar'
不要用 ||= 去初始化boolean型变量。
12345
# bad - would set enabled to true even if it was falseenabled||=true# goodenabled=trueifenabled.nil?
classParent@@class_var='parent'defself.print_class_varputs@@class_varendendclassChild<Parent@@class_var='child'endParent.print_class_var# => will print "child"
classTestClass# baddefTestClass.some_method# body omittedend# gooddefself.some_other_method# body omittedend
避免使用 class << self , 除非是必须的, 比如单独的accessors和aliased属性。
1234567891011121314151617181920212223242526
classTestClass# badclass<<selfdeffirst_method# body omittedenddefsecond_method_etc# body omittedendend# goodclass<<selfattr_accessor:per_pagealias_method:nwo,:find_by_name_with_ownerenddefself.first_method# body omittedenddefself.second_method_etc# body omittedendend
string="some injection\nusername"string[/^username$/]# matchesstring[/\Ausername\Z/]# don't match
使用 x 来修饰复杂的正则, 这样更可读,还可加注释,只是需要小心空格
1234567
regexp=%r{ start # some text \s # white space char (group) # first group (?:alt1|alt2) # some alternation end }x
百分号字面量 (Percent Literals)
使用%w毫无压力
1
STATES=%w(draft open closed)
使用%()来引用单行字符串,相当于双引号(相当于%Q()),对于多行的字符串,要使用here文档。
1234567891011121314
# bad (no interpolation needed)%(<div class="text">Some text</div>)# should be '<div class="text">Some text</div>'# bad (no double-quotes)%(This is #{quality} style)# should be "This is #{quality} style"# bad (multiple lines)%(<div>\n<span class="big">#{exclamation}</span>\n</div>)# should be a heredoc.# good (requires interpolation, has quotes, single line)%(<tr><td class="name">#{name}</td>)
超过一个/符合的正则应该使用 %r
123456789
# bad%r(\s+)# still bad%r(^/(.*)$)# should be /^\/(.*)$/# good%r(^/blog/2011/(.*)$)