How to Find If a String Starts with Another String in Ruby

How to check whether a string contains a substring in Ruby

You can use the include? method:

my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end

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

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 _. On Rails you can use the alias String#starts_with? (note the plural - and note that this method is deprecated). Personally, I'd prefer String#starts_with? over the actual String#start_with?

Check if string starts with X letter in Ruby

You can use String#start_with? method

'String'.start_with? 'S'
=> true

Also you can list possible variants of beginning

'String'.start_with? 'E', 'S'
=> true

How to check if a string begins with prefix and contains specific keyword in Ruby

The code looks good. The only feedback I have is regarding the use of 'include?' function for the prefix. Try to use 'start_with?' function instead, so that you don't get True even when the the "Dr" is within the string.

def match st
if st.start_with?('Dr.') and st.include?('Alex')
return true
else
return false
end
end

How to tell what Ruby string starts with?

If you mean checking if first element in string is letter, you could do:

string[0].match(/[a-zA-Z]/)

or, as Arup Rakshit suggested, you can use i option in your regexp to ignore case:

string[0].match(/[a-z]/i)

These lines will return either MatchData if tested string starts with letter or nil if it doesn't. If you want true and false values, you can do:

!!string[0].match(/[a-z]/i)

Testing whether string starts with or end with another string

There are built in methods:

"String".start_with? "S" # true
"String".end_with? "4" # false

Check whether a string contains all the characters of another string in Ruby

Sets and array intersection don't account for repeated chars, but a histogram / frequency counter does:

require 'facets'

s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 }
#=> true

Write your own Array#frequency if you don't want to the facets dependency.

class Array
def frequency
Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
end
end


Related Topics



Leave a reply



Submit