Ruby on Rails是一个功能强大的WEB开发框架,在这里我们将会学到一些经常用到的Ruby on Rails内置方法,帮助大家熟练掌握其应用技巧。
Ruby on Rails自动生成文档技巧大讲堂 Ruby代码管理经验分享 Ruby创建构造器技巧分享 Ruby异常处理结构特点介绍 Ruby数学表达式中各种应用解析
Ruby on Rails内置方法之对象是否为空blank?
puts [ ].blank? #=> true puts { 1 => 2}.blank? #=> false puts " cat ".blank? #=> false puts "".blank? #=> true puts " ".blank? #自动去除前后空格=> true puts nil.blank? #=> true
Ruby on Rails内置方法之排序:group_by()
groups = posts.group_by {|post| post.author_id}
Ruby on Rails内置方法之组句:to_sentence()
puts [ "ant", "bat", "cat"]. to_sentence #=> "ant, bat, and cat" puts [ "ant", "bat", "cat"]. to_sentence(:connector => "and not forgetting") #=> "ant, bat, and not forgetting cat" puts [ "ant", "bat", "cat"]. to_sentence(:skip_last_comma => true) #=> "ant, bat and cat"
Ruby on Rails内置方法之分组:in_groups_of()
[1,2,3,4,5,6,7].in_groups_of(3) {|slice| p slice} #=> [1, 2, 3] [4, 5, 6] [7,nil, nil] [1,2,3,4,5,6,7].in_groups _of(3,"X") {|slice| p slice} #=> [1, 2, 3] [4, 5, 6] [7,"X", "X"]
Ruby on Rails内置方法之字符串方法:
string = "Now is the time" puts string.at(2) #=> "w" puts string.from(8) #=> "he time" puts string.to(8) #=> "Now is th" puts string.first #=> "N" puts string.first(3) #=> "Now" puts string.last #=> "e" puts string.last(4) #=> "time" puts string.starts_with?("No") #=> true puts string.ends_with?("ME") #=> false count = Hash.new(0) string.each_char {|ch| count[ch] += 1} p count #=> {" "=>3, "w"=>1, "m"=>1, "N"=>1, "o"=>1, "e"=>2, "h"=>1, "s"=>1, "t"=>2, "i"=>2}
转载:
https://developer.51cto.com/art/200912/170449.htm