How to ignore uppercase letters with start_with?

Is there a better way to ignore uppercase letters than this?

"Hello".start_with?("hell","Hell") #=> true 

I want to check if a string element in an array starts with another string ignoring an uppercase letter, like LIKE % in MySQL.

+4
source share
3 answers

I would do something like this:

 'Hello'.upcase.start_with?('HELL') 

Another approach to the same problem. This is equivalent to doing something like UPPER(column) like 'SOMETHING%' in SQL.

+4
source

You can use regex with String#=~ :

 "Hello" =~ /^hell/i #=> 0 "hELLO" =~ /^hell/i #=> 0 "world" =~ /^hell/i #=> nil 

Since 0 is true and nil is false, this can be used in the if clause:

 if str =~ /^hell/i # starts with hell end 
+5
source

I think it's best to use a combination of Ruby regular expressions with the ignore flag flag:

 'Hello'.match /^hell/i 

"^" indicates the beginning of a line. Without it, it will correspond to "hell" anywhere in the line. And the last ā€œiā€ is just a regular expression flag indicating a match for the ignore character set.

Information on the Ruby Regex API can be found here: http://www.regular-expressions.info/ruby.html

0
source

Source: https://habr.com/ru/post/1498582/


All Articles