Reputation: 1118
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
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
Reputation: 59113
Consider using the method start_with?
.
s = "990822"
=> "990822"
s.start_with? "99"
=> true
Upvotes: 4
Reputation: 23317
You can use a range to access string:
"990822"[0...2]
# => "99"
See the String
docs
Upvotes: 3