Forum: Ruby String keys in hash

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.
B182501507864b32d5242cf0350902b2?d=identicon&s=25 Konlin (Guest)
on 2006-03-19 15:15
(Received via mailing list)
Hi all,

My rails app is going to count sth based on poll id in the url. The url
looks like:
http://address.com?id=dwNKiItvcyrQ5sycnIhmJablDfXs...

In a controller, I've created a hash where the keys are the ids:

@codes = {
         'dwNKiItvcyrQ5sycnIhmJablDfXsc9tshaGIVyNIei7.e7' =>
         {:partner_id => 0,
         :partner_name => 'sth',
         :page_number => 1},
         ...
         }

Then i do:

poll_id = '"' + params['id'] + '"'

The problem is, @codes[poll_id] returns nil.

Otherwise, @codes["dwNKiItvcyrQ5sycnIhmJablDfXsc9tshaGIVyNIei7.e7"]
works ok. What am I doing wrong if the keys are the same and explicite
string works while variable doesn't?

Can you explain me that and write how to solve that problem?

Thanks in advance, greetz

--
K.O.N.L.I.N.            konlin@post.pl
   Kinetic Organism Normally for Logical Infiltration and Nullification,

          "Day after day, love turns grey
           Like the skin of a dying man"
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2006-03-19 15:26
(Received via mailing list)
On 19-Mar-06, at 9:13 AM, Konlin wrote:

>
> poll_id = '"' + params['id'] + '"'
>
> The problem is, @codes[poll_id] returns nil.

You should be able to say

   @codes[params['id']]

to access the hash.

>
> Otherwise, @codes["dwNKiItvcyrQ5sycnIhmJablDfXsc9tshaGIVyNIei7.e7"]
> works ok. What am I doing wrong if the keys are the same and explicite
> string works while variable doesn't?
>
> Can you explain me that and write how to solve that problem?
>
> Thanks in advance, greetz

The quotes in @codes
["dwNKiItvcyrQ5sycnIhmJablDfXsc9tshaGIVyNIei7.e7"] are part of Ruby's
syntax not the string.  For example in this irb session:

ratdog:~ mike$ irb
irb(main):001:0> puts "hello"
hello
=> nil

The quotes are needed to indicate that the characters h e l l o are a
string.  The string which ruby uses doesn't contain the quotes.

Does that help?

Mike


--

Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
Ee5c1f36549c4ddca2189f9c4cf36f2c?d=identicon&s=25 Scott (Guest)
on 2006-03-19 16:13
(Received via mailing list)
Why are you wrapping params['id'] in double quotes?  If params['id'] is
already equal to your key in @codes, you can just use:

@codes[params['id']]

-Scott
This topic is locked and can not be replied to.