Ruby常用方法


count
判断内容l的个数integer型

full_name.count("l")     //full_name ="full"

include?
判断内容是否有l,boolean型

full_name.include?("l")   //full_name ="full"

equal?

equal?方法用来判断2个对象是否是同一个对象
a.equal? b相当于判断"a就是b"

2.1.1 :005 > "a" == "a"
 => true 
2.1.1 :006 > "a".equal? "a"
 => false 
2.1.1 :007 > :a.equal? :a
 => true 

size
size内容的个数

full_name.size

upcase、downcase、 swapcase

str="aBC"
irb(main):036:0> str.upcase  #全部大写
=> "ABC"
irb(main):037:0> str.downcase #全部小写
=> "abc"
irb(main):038:0> str.swapcase #字母大小写转换
=> "Abc"

-------

irb(main):067:0> str="aBcD"
=> "aBcD"

irb(main):068:0> str.swapcase
=> "AbCd"

irb(main):069:0> str=str.lstrip
=> "aBcD"

irb(main):072:0> puts str.rjust(10,'.')
......aBcD

irb(main):073:0> puts str.ljust(10,'.')
aBcD......

irb(main):074:0> puts str.center(10,'.')
...aBcD...

irb(main):078:0> str.split(//)
=> ["a", "B", "c", "D"]

类型转换

ruby的整数、浮点数、字符串的类均提供了to_i,to_f,to_s三个方法,分别用于转换成整数、转换成浮点数、转换成字符串.
浮点数转换成整数,会强行去掉小数点后面的数字
irb(main):017:0> 123.45.to_i
=> 123

整数转换成浮点数,会添加小数点和0
irb(main):018:0> 123.to_f
=> 123.0

整数转换成字符串
irb(main):019:0> 123.to_s
=> "123"

浮点数转换成字符串
irb(main):020:0> 123.45.to_s
=> "123.45"

浮点数转换成字符串,会去掉最后多余的0
irb(main):021:0> 123.1230.to_s
=> "123.123"

字符串转换成整数,以字符开头的,转换不了返回0
irb(main):022:0> "sharejs.com-001".to_i
=> 0

以数字开头的字符串转换成浮点数
irb(main):024:0> "123.45sharejs.com".to_f
=> 123.45

以数字开头的字符串转换成整数
irb(main):025:0> "123.45sharejs.com".to_i
=> 123

irb(main):094:0> puts :derek.object_id
554568

irb(main):092:0> puts :derek.class
Symbol

irb(main):091:0> puts :derek.to_s
derek

puts array_4.join(“,”)


ruby中nil?, empty? , blank?

.nil? 和 .empty? 是 ruby的方法
.blank? 是 rails的方法
.nil? ==> 判断对象是否存在(nil)。不存在的对象都是nil的
.empty? ==>  对象已经存在,判断是否为空字段,比如一个字符串是否为空串,或者一个数组中是否有值。
.blank? ===> 相当于同时满足 .nil? 和 .empty? 。railsAPI中的解释是如果对象是:false, empty, 空白字符. 比如说: "", " ", nil, [], 和{}都算是blank。   (object.blank? 相当于 object.nil?||object.empty?)
if !address.nil? && !address.empty?  ===> if !address.blank?
.nil 
-----------

.nil?

- It is Ruby method
- It can be used on any object and is true if the object is nil.
- "Only the object nil responds true to nil?" - RailsAPI

nil.nil? = true
anthing_else.nil? = false
a = nil
a.nil? = true
“”.nil = false

.empty?

- It is Ruby method
- can be used on strings, arrays and hashes and returns true if:
String length == 0
Array length == 0
Hash length == 0

- Running .empty? on something that is nil will throw a NoMethodError

"".empty = true
" ".empty? = false


.blank?

- It is Rails method
- operate on any object as well as work like .empty? on strings, arrays and hashes.

nil.blank? = true 
[].blank? = true 
{}.blank? = true 
"".blank? = true 
5.blank? == false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值