Simple way to switch between printing object key/reference andobject value?

N

Nicholas Orr

Hi,

I have a hash:

ruby-1.8.7-p249 > person =
{"name"=>"nick","age"=>26,"country"=>"australia","job"=>{"position"=>"it
guy","start"=>"2010-01-01"},"roles"=>["admin","user","login"]}
=> {"name"=>"nick", "country"=>"australia", "job"=>{"position"=>"it
guy", "start"=>"2010-01-01"}, "roles"=>["admin", "user", "login"],
"age"=>26}

I have an instance variable: @debug
when @debug is true I should get the key/reference that is being
called, when it is false I should get the value, like this

ruby-1.8.7-p249 > @debug = false
=> false
ruby-1.8.7-p249 > puts "Name: #{@debug ? "person['name']" : person["name"]}"
Name: nick
=> nil
ruby-1.8.7-p249 > puts "Position: #{@debug ?
"person['job']['position']" : person["job"]["position"]}"
Position: it guy
=> nil
ruby-1.8.7-p249 > @debug = true
=> true
ruby-1.8.7-p249 > puts "Name: #{@debug ? "person['name']" : person["name"]}"
Name: person['name']
=> nil
ruby-1.8.7-p249 > puts "Position: #{@debug ?
"person['job']['position']" : person["job"]["position"]}"
Position: person['job']['position']
=> nil

This works great for one of things - typing out the if
@debug..then..else - however I need to do this all the time and I'm
looking for a way to do it automatically or DRY.
a simple method that looks at the @debug state then either outputs the
value or the reference, is it possible or do I just have to do it the
way I've shown above?
The person hash is always called person and is also an instance
variable if that helps...

DRY = ref_or_value("person['job']['position']") ??


Thanks,

Nick
 
B

Brian Candler

Nicholas said:
when @debug is true I should get the key/reference that is being
called, when it is false I should get the value, like this

ruby-1.8.7-p249 > @debug = false
=> false
ruby-1.8.7-p249 > puts "Name: #{@debug ? "person['name']" :
person["name"]}"
Name: nick
=> nil
ruby-1.8.7-p249 > @debug = true
=> true
ruby-1.8.7-p249 > puts "Name: #{@debug ? "person['name']" :
person["name"]}"
Name: person['name']
=> nil

I think it would be too dangerous to override person.[]. What about when
you need to access the real value? I suppose if you use person.name and
keep person['name'] only for display purposes it might be OK.

If this is just for debugging, I'd be inclined to override
Person#inspect
DRY = ref_or_value("person['job']['position']") ??

You could do:

dry = person.ref_or_value('job','position')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top