|
Using a variable as a hash index
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, you will often want to access a hash data structure.
However rather than explicitly accessing an element (hash["field"]) you will
want to use a variable in place of the explicit text/string of the field
name.
If on tries to do this, (in the example below, we are testing a desired hash
field for nil - where in this case field is our variable name) you might think that one of the following would
work:
hash.field.nil?
or
hash[field].nil?
Surprisingly, this is not the case. Instead, you must do the following in
order for a variable to be used to access a hash element:
hash.send(field).nil?
.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|
|
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.
|