How do I find if a string starts with another string in Ruby?

前端 未结 4 615
小鲜肉
小鲜肉 2020-12-13 08:02

What the best way to find if a string starts with another in Ruby (without rails)?

4条回答
  •  無奈伤痛
    2020-12-13 08:30

    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.

    'abcdefg' =~  /\Aabc/ 
    

提交回复
热议问题