Forum: Ruby isset kinda function

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alexandru C. (Guest)
on 2006-06-05 14:31
Looking for something like PHP's isset.
Alexandru C. (Guest)
on 2006-06-05 14:56
Alex Copot wrote:
> Looking for something like PHP's isset.

And something like print_r to display an array.
Florian GroÃ? (Guest)
on 2006-06-05 15:26
(Received via mailing list)
Alex Copot wrote:

> Looking for something like PHP's isset.

defined?() will work, but usually you won't need it. Depending on what
you are trying to do there likely is better solutions.
Alexandru C. (Guest)
on 2006-06-05 15:28
Well, I have something like this

    if session[:cart][product_id] > 1
      session[:cart][product_id] = session[:cart][product_id] + 1
    else
      session[:cart][product_id] = 1
    end

But it doesn't work. I get this.

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.[]
Florian GroÃ? (Guest)
on 2006-06-05 15:32
(Received via mailing list)
Alex Copot wrote:

> And something like print_r to display an array.

Try p(obj) for debug output. You can also do this:

require 'yaml'; y(obj)
Florian GroÃ? (Guest)
on 2006-06-05 15:38
(Received via mailing list)
Alex Copot wrote:

> You have a nil object when you didn't expect it!
> You might have expected an instance of Array.
> The error occured while evaluating nil.[]

Seems like session[:cart] is nil. You can just do

if session[:cart] then
   ...
end

And things will work correctly.

What you proably want is to initialize session[:cart] to an object,
though. You can do that like:

session[:cart] ||= default

Hope this helps.
Alexandru C. (Guest)
on 2006-06-05 15:39
Thank you very much.


Florian GroÃ? wrote:
> Alex Copot wrote:
>
>> You have a nil object when you didn't expect it!
>> You might have expected an instance of Array.
>> The error occured while evaluating nil.[]
>
> Seems like session[:cart] is nil. You can just do
>
> if session[:cart] then
>    ...
> end
>
> And things will work correctly.
>
> What you proably want is to initialize session[:cart] to an object,
> though. You can do that like:
>
> session[:cart] ||= default
>
> Hope this helps.
This topic is locked and can not be replied to.