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.
9bd3a6bbea1330d30e6a46009bf27097?d=identicon&s=25 Alexandru Copot (copot)
on 2006-06-05 12:31
Looking for something like PHP's isset.
9bd3a6bbea1330d30e6a46009bf27097?d=identicon&s=25 Alexandru Copot (copot)
on 2006-06-05 12:56
Alex Copot wrote:
> Looking for something like PHP's isset.

And something like print_r to display an array.
E0ed615bd6632dd23165e045e3c1df09?d=identicon&s=25 Florian GroÃ? (Guest)
on 2006-06-05 13: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.
9bd3a6bbea1330d30e6a46009bf27097?d=identicon&s=25 Alexandru Copot (copot)
on 2006-06-05 13: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.[]
E0ed615bd6632dd23165e045e3c1df09?d=identicon&s=25 Florian GroÃ? (Guest)
on 2006-06-05 13: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)
E0ed615bd6632dd23165e045e3c1df09?d=identicon&s=25 Florian GroÃ? (Guest)
on 2006-06-05 13: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.
9bd3a6bbea1330d30e6a46009bf27097?d=identicon&s=25 Alexandru Copot (copot)
on 2006-06-05 13: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.