problem in hash and symbol

A

Amir Ebrahimifard

Hi everybody
I have a question about hash and symbol. when I use symbol for key in
hash , it didn't for me. what is the problem ?

(example : hash = { :eek:dd => [ 1 , 3 , 5 ] , :even => [ 2 , 4 , 6 ] , :7
=> "chance" , "number" => 1 } )
 
J

Jesús Gabriel y Galán

Hi everybody
I have a question about hash and symbol. when I use symbol for key in
hash , it didn't for me. what is the problem ?

(example : hash = { :eek:dd => [ 1 , 3 , 5 ] , :even => [ 2 , 4 , 6 ] , :7
=> "chance" , "number" => 1 } )

A symbol cannot start with a number:

irb(main):005:0> :7
SyntaxError: compile error
(irb):5: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT
or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
from (irb):5
from :0
irb(main):006:0> :7y
SyntaxError: compile error
(irb):6: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT
or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
from (irb):6
from :0

Jesus.
 
C

Christopher Dicely

Hi everybody
I have a question about hash and symbol. when I use symbol for key in
hash , it didn't for me. what is the problem ?

(example : hash = { :eek:dd => [ 1 , 3 , 5 ] , :even => [ 2 , 4 , 6 ] , :7
=> "chance" , "number" => 1 } )

Looking at that, you've got two symbols :)odd, :even) used as keys, a
string ("number") used as a key, and a great big honking syntax error
:)7) where a key should be. If you want to use the string "7"
converted to a symbol (whether its as a key or otherwise), the Ruby
syntax for that is :"7", the only symbols that don't need quotes are
ones that would be valid ruby identifiers -- and 7, standing alone, is
an integer, not an identifier.

So the hash {:eek:dd => [1, 3, 5], :even => [2, 4, 6], :"7" => "chance",
"number" => 1} seems to (maybe) be what you're looking for.
 
R

Ryan Davis

Hi everybody
I have a question about hash and symbol. when I use symbol for key in
hash , it didn't for me. what is the problem ?
=20
(example : hash =3D { :eek:dd =3D> [ 1 , 3 , 5 ] , :even =3D> [ 2 , 4 , 6 = ] , :7
=3D> "chance" , "number" =3D> 1 } )

what isn't working for you? the :7 ? that's not valid syntax for ruby =
symbols. You'll have to use the :"extended symbol" notation:
hash =3D { :eek:dd =3D> [ 1 , 3 , 5 ] , :even =3D> [ 2 , 4 , 6 ] , =
:"7" =3D> "chance" , "number" =3D> 1 }
=3D> {"number"=3D>1, :"7"=3D>"chance", :eek:dd=3D>[1, 3, 5], :even=3D>[2, =
4, 6]}
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top