Forum: Ruby creating a hash key with a variable name?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6baa3299d90dc0d50940e8d14e828964?d=identicon&s=25 terry (Guest)
on 2007-02-21 16:55
(Received via mailing list)
Is it possible that I could do the following, if so what is the
correct syntax?

aHash = Hash.new
aString = "BasketballTeam"
aHash[aString] => "Bulls"
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2007-02-21 17:07
(Received via mailing list)
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.  ;)  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 Gray II
2f24c382600d9fd71085a74251fd5a39?d=identicon&s=25 Damian Terentyev (Guest)
on 2007-02-22 13:47
(Received via mailing list)
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
This topic is locked and can not be replied to.