hash key (?)

B

Brent Clark

Hiya

Im going through the Ruby Cookbook.

On page 51, there is the following example

letter = { ?v => 'aeiou', ?c => 'xyz' }

My question is, what does the key ?v do or mean.

Kind Regards
Brent Clark
 
J

Jesús Gabriel y Galán

Hiya

Im going through the Ruby Cookbook.

On page 51, there is the following example

letter = { ?v => 'aeiou', ?c => 'xyz' }

My question is, what does the key ?v do or mean.

irb(main):008:0> ?v.class
=> Fixnum
irb(main):009:0> ?v
=> 118
irb(main):010:0> "v"[0]
=> 118

It's a literal that contains the numeric value of the character v

Jesus.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Hiya

Im going through the Ruby Cookbook.

On page 51, there is the following example

letter = { ?v => 'aeiou', ?c => 'xyz' }

My question is, what does the key ?v do or mean.

Kind Regards
Brent Clark
In earlier versions of Ruby, prefixing a character with a question mark was
sort of a literal for a given character. I just checked irb for 1.8.6 and
1.8.7, ?v would return 118, which is the ascii value of the character v, and
in 1.9.1 it returned "v" the one character String. Another place you can see
this shift take place is in String#[] where you might say "vat"[0] in 1.8
you would get 118, and in 1.9 you would get "v"

A more idiomatic alternative would probably be to use symbols as hash keys.
letter = { :vowels => 'aeiou' , :consonants => 'xyz' }
(I don't have the book, I'm guessing as to what ?v and ?c are supposed to
mean)
 
E

Eugen Ciur

It returns ASCII code following for character question mark:
For example:
irb(main):002:0> ?a
=> 97
 

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

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
EmeliaBryc

Latest Threads

Top