15 Volts
15 Volts

Reputation: 2077

How to use ? syntax in Ruby while creating a String

While reading the documentation for sort_by, I came up with:

  files = Dir["*"]
  sorted = files.sort { |a, b|
    test(?M, a) <=> test(?M, b)
  }
  sorted   #=> ["mon", "tues", "wed", "thurs"]

As far as ?M goes, it just creates a string "M":

> ?\\
# => "\\"

> ?A
# => "A"

> ?1
# => "1"

> ?Hi!
SyntaxError ((irb):45: syntax error, unexpected '?')

> ?H 'i!'
# => "Hi!"

So what's the proper usage of the ? syntax in Ruby?

Upvotes: 1

Views: 65

Answers (1)

Rein Avila
Rein Avila

Reputation: 405

The syntax ?x where x is any single character, will result to a single character string. ?x is a shortcut for 'x'. Try replacing ?M with 'M' in your code. It should have the same output.

files = Dir["*"]
sorted = files.sort { |a, b|
  test('M', a) <=> test('M', b)
}
sorted

Reference:

There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding.

https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html

Upvotes: 3

Related Questions