优先级总结:

1.关键字类如if and 等的优先级是要比符号类低;

2.赋值符号= ||=等优先级也比较低,仅次于关键字类;

3.[] []=元素引用的优先级非常高。

代码示例:

#puts {}.class 实际上相当于 (puts {}).class -> nil.class 所以输出为空。{}相当于一个空的 block,优先和方法 puts 结合
puts {}.class #NilClass

#优先级:&& > = > and
a = 5 && 3 #a = ( 5 && 3)
b = 5 and 3 #( b = 5 ) and 3

Rails项目中的应用

#下面的代码会出现Can only render or redirect once per action问题
def demo
  if true
    redirect_to root_path
  end
  redirect_to root_path
end

解决问题的方式是利用优先级and return

def demo
  if true
    redirect_to root_path and return
  end
  redirect_to root_path
end

解释,上面的代码中方法执行的优先级比and高,即上面的代码执行为

(redirect_to root_path) and return

但是()中的内容返回的肯定为true, 所以必然会执行and后面的内容,所以上面的代码内容返回,并不会执行后面的代码

参考文章:http://xiewenwei.github.io/blog/2012/11/25/rubyde-yun-suan-fu-he-yu-ju-you-xian-ji/

results matching ""

    No results matching ""