Isset kinda function


#1

Looking for something like PHP’s isset.


#2

Alex Copot wrote:

Looking for something like PHP’s isset.

And something like print_r to display an array.


#3

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.


#4

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.[]


#5

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.


#6

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.


#7

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)