开发者

using nil or [] on rails 2.3.8

开发者 https://www.devze.com 2023-01-25 19:30 出处:网络
I\'ve a strange situation with my rails application (2.3.8) I want to assign a no nil value to some variable in my controller, so I wrote this code:

I've a strange situation with my rails application (2.3.8)

I want to assign a no nil value to some variable in my controller, so I wrote this code:

@myValue = session[:value] or []

In my view I wrote:

<%= @myvalue.size %>

When I display my page, I have a nil error.

I've tried the nil or [] in the IRB and I get the []. So my question is if anyone know 开发者_如何学Gowhy is working different in rails?

P.S.: The only gem that I'm using is cell version 3.3.3.

Thanks!


The 'or' keyword has too low a precedence for this code to work. Use '||' instead. To demonstrate the point:

ruby-1.9.2-p0 > a = nil or true; a
 => nil 
ruby-1.9.2-p0 > a = nil || true; a
 => true 


It's an order of operations thing.

@myValue = (session[:value] or []) will work. I believe @myValue = session[:value] or [] is interpreted as (@myValue = session[:value]) or []. But @myValue = session[:value] || [] worked too without parens. || has higher precedence than or.


The idiom is to do session[:value] || [], using ||, not or. You can also try session[:value].to_a. This works because nil.to_a becomes [].

0

精彩评论

暂无评论...
验证码 换一张
取 消