Ricardo Green
Ricardo Green

Reputation: 1118

How do you get the first two characters of a string?

I have a string "990822". I want to know if the string starts with "99".

I could achieve this by getting the first two characters of the string, then check if this is equal to "99". How do I get the first two characters from a string?

Upvotes: 0

Views: 857

Answers (4)

sawa
sawa

Reputation: 168091

To get the first two characters, the most straightforward way is:

"990822"[0, 2] # => "99"

Using a range inside the method [] is both not straightforward and also creates a range object that is immediately thrown out, which is a waste.

However, the whole question is actually an XY-question.

Upvotes: 2

Xero
Xero

Reputation: 4175

You can use String#start_with?:

"990822".start_with?("99") #=> true

Upvotes: 9

khelwood
khelwood

Reputation: 59113

Consider using the method start_with?.

s = "990822"
  => "990822"
s.start_with? "99"
  => true

Upvotes: 4

mrzasa
mrzasa

Reputation: 23317

You can use a range to access string:

"990822"[0...2]
# => "99"

See the String docs

Upvotes: 3

Related Questions