Does Ruby have a string.startswith(“abc”) built in method?

后端 未结 4 1099
轻奢々
轻奢々 2020-12-23 12:41

Does Ruby have a some_string.starts_with(\"abc\") method that\'s built in?

相关标签:
4条回答
  • 2020-12-23 13:17

    If this is for a non-Rails project, I'd use String#index:

    "foobar".index("foo") == 0  # => true
    
    0 讨论(0)
  • 2020-12-23 13:22

    Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

    You could always use a regular expression though:

    if SomeString.match(/^abc/) 
       # SomeString starts with abc
    

    ^ means "start of string" in regular expressions

    0 讨论(0)
  • 2020-12-23 13:22

    You can use String =~ Regex. It returns position of full regex match in string.

    irb> ("abc" =~ %r"abc") == 0
    => true
    irb> ("aabc" =~ %r"abc") == 0
    => false
    
    0 讨论(0)
  • 2020-12-23 13:30

    It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

    0 讨论(0)
提交回复
热议问题