ruby基础

1、 render

一下三种渲染方式的渲染结果是一样的:

    render(:text=>"<h1>hello world!</h1>")
    
    render text:"<h1>hello world!</h1>"
    
    render html:"<h1>hello world!</h1>".html_safe

渲染结果:

render html:"<h1>hello world!</h1>"

渲染结果:

所以,在返回html时,如果不调用html_safe方法,html是无法正确解析的。

2、empty、blank

"somestring".empty?=>false

"".empty?=>true

nil.empty?=>NoMethodError: undefined method `empty?' for nil:NilClass(nil不支持empty方法)

nil.to_s.empty?=>true

"    ".empty?=>false

"    ".blank?=>true

nil.blank?=>true

3、nil

nil.nil?=>true

xx.nil?=>false(除了nil以外所有对象nil的结果都为false)

同理,除了!!nil=>false以外,所有的!!xx都为true,包括!!0=>true

4、unless

和if not相对应,if是在后面添加为真时执行,而unless是在后面条件返回值为false时才会执行

 5、! bang

a = [42, 8, 17]

a.sort=>[8,17,42]

a=>[42,8,17] #执行sort方法时,对象a本身并没有发生变化

a.sort!=>[8,17,42]

a=>[8,17,42] #执行sort!方法时,对象a本身也变化了,这就是所谓的炸弹(bang!)方法

6、运算符

除法运算符, 1/10 ->0     9/10->0

在ruby中,两个整数类型的数字进行运算,得到的结果默认仍然是整数,而且没有四舍五入,所以在ruby中如果两个整数进行除法运算,而且希望可以得到精确值,应该想将其中一个数字转换为浮点数再进行运算,例如:1/10.0->0.1

posted @ 2016-12-08 16:12  tzdk  阅读(197)  评论(0编辑  收藏  举报