Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

hash key (?)

0 views
Skip to first unread message

Brent Clark

unread,
Jul 29, 2010, 7:59:48 AM7/29/10
to
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

Jesús Gabriel y Galán

unread,
Jul 29, 2010, 8:34:10 AM7/29/10
to
On Thu, Jul 29, 2010 at 1:59 PM, Brent Clark <brentgc...@gmail.com> wrote:
> 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.

Josh Cheek

unread,
Jul 29, 2010, 8:50:09 AM7/29/10
to
[Note: parts of this message were removed to make it a legal post.]

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)

Eugen Ciur

unread,
Jul 29, 2010, 8:50:32 AM7/29/10
to
It returns ASCII code following for character question mark:
For example:
irb(main):002:0> ?a
=> 97
0 new messages