几种常见Ruby on Rails内置方法介绍

2021/7/19 9:06:58

本文主要是介绍几种常见Ruby on Rails内置方法介绍,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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



这篇关于几种常见Ruby on Rails内置方法介绍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程