Creating a hash key with a variable name?

Is it possible that I could do the following, if so what is the
correct syntax?

aHash = Hash.new
aString = “BasketballTeam”
aHash[aString] => “Bulls”

On Feb 21, 2007, at 9:55 AM, terry wrote:

Is it possible that I could do the following, if so what is the
correct syntax?

aHash = Hash.new
aString = “BasketballTeam”
aHash[aString] => “Bulls”

Drop the greater than symbol in the last line:

aHash[aString] = “Bulls”

And sense we are talking, allow me to explain the variable naming
conventions for Ruby. :wink: We prefer to use snake_case for variable
and method names and save the CamelCase for class and module names.
Doing that, I would rewrite your code as:

a_hash = Hash.new
a_string = “BasketballTeam”
a_hash[a_string] = “Bulls”

Of course, “a_hash” and “a_string” don’t really tell us much, so
let’s go a step further and try to pick variable names that inform us
of what we are working with:

teams = Hash.new
team_type = “BasketballTeam”
teams[team_type] = “Bulls”

I think that reads a lot better, but you be the judge.

Hope that helps.

James Edward G. II

Hi,

On Feb 21, 2007, at 9:55 AM, terry wrote:

Is it possible that I could do the following, if so what is the
correct syntax?

It is also better to use Ruby Symbols instead of strings as hash keys,
so the line would probably be
team_type = :BasketballTeam

I think what Terry meant was… let’s say we have an id and want to use it as a key value inside an object:

my_id = "123"

some_object = {
    "123": {
        object_name: 'John',
        object_foo_bar: 'Some string'
    }
}

For this you should use rocket object format:

some_object = {
    my_id => {
        object_name: 'John',
        object_foo_bar: 'Some string'
    }
}