jeroen
1
Hi,
Is there a way to test if a certain (local) variable has been
initialized?
I’d like to do something like
if isset(myvar) and myvar.true?
#some code
else
#default behaviour
end
I have a lot of shared views that I call with params such as {
show_pager => true
Instead of having to explicitly say show_pager => false it should be
possible to make false a default value, right?
Jeroen
jeroen
2
Jeroen H. wrote:
Hi,
Is there a way to test if a certain (local) variable has been
initialized?
I’d like to do something like
if isset(myvar) and myvar.true?
#some code
else
#default behaviour
end
I have a lot of shared views that I call with params such as {
show_pager => true
Instead of having to explicitly say show_pager => false it should be
possible to make false a default value, right?
Jeroen
The default value is nil, and thus false.
if myvar
#some code
else
#default behaviour
end
Works.
Jules.
jeroen
3
The default value is nil, and thus false.
if myvar
#some code
else
#default behaviour
end
Works.
That works with @instance vars, but not local vars. You’ll get a
NameError. You can do this, however:
if defined?(my_var)
else
end
–
Rick O.
http://techno-weenie.net
jeroen
4
irb(main):001:0> hash = {‘a’ => 1, ‘b’ => 2}
=> {“a”=>1, “b”=>2}
irb(main):003:0> hash[‘c’]
=> nil
irb(main):004:0>
jeroen
5
Not positive but Rails provides a blank? method. Check it out.
Bob S.
http://www.railtie.net/
jeroen
6
Rick O. wrote:
That works with @instance vars, but not local vars. You’ll get a
NameError.
Exactly.
You can do this, however:
if defined?(my_var)
else
end
Great, this is what I was looking for. I did look in the Ruby docs, but
could find anything under class Object, which class does defined? belong
to?
Jeoen
jeroen
7
On 2/02/2006, at 10:25 AM, Jeroen H. wrote:
Great, this is what I was looking for. I did look in the Ruby docs,
but could find anything under class Object, which class does
defined? belong to?
It’s a language thing, it doesn’t belong to any object. Not as far as
I can grep anyway.
jeroen
8
Jules J. wrote:
irb(main):001:0> hash = {‘a’ => 1, ‘b’ => 2}
=> {“a”=>1, “b”=>2}
irb(main):003:0> hash[‘c’]
=> nil
irb(main):004:0>
But this hash has already been initialized. I meant for local possibly
uninitialized vars.
if myvar then puts ‘true’ else puts ‘false’ end
NameError: undefined local variable or method `myvar’ for
#Object:0x13d9b8
from (irb):2
jeroen
9
defined? is an operator just like &&, and, or etc…
Page 88 of the Pickaxe (116 in the PDF)
Bob S.
http://www.railtie.net/
jeroen
10
Rick O. wrote in post #29743:
The default value is nil, and thus false.
if myvar
#some code
else
#default behaviour
end
Works.
That works with @instance vars, but not local vars. You’ll get a
NameError. You can do this, however:
if defined?(my_var)
else
end
–
Rick O.
http://techno-weenie.net
Effective Answer
Mukto