What the best way to find if a string starts with another in Ruby (without rails)?
相关问题
- how to split a list into a given number of sub-lis
- Generate string from integer with arbitrary base i
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
相关文章
- JSP String formatting Truncate
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- Selecting only the first few characters in a strin
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
[edit] This is something I didn't know before this question:
start_with
takes multiple arguments.Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:
So it looks like
start_with?
ist the fastest of the bunch.Updated results with Ruby 2.2.2p95 and a newer machine:
I like
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.