Ruby: return the first character from string if it matches and if there is no match then return nil?

Muhammad Umer

is there a built in way to get first match or nil for a character from string.

i can get a first character like this

'word'.match('o').to_s

but if there is no match it gives "" not nil

Stefan

Use String#[match_str]:

If a match_str is given, that string is returned if it occurs in the string.

Returns nil if (...) the match string cannot be found.

'word'['o'] #=> 'o'
'word'['q'] #=> nil

The [] method is very versatile, you can also pass a regular expression or indices in different ways.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Elasticsearch return exact match first then other matches

return string with first match Regex

Ruby on rails return a string if a model attribute is nil

return matches if match

Return range with first and last character in string

return the first non repeating character in a string in javascript

How to return first match sub-string of a string using Ruby regex?

In Raku, doesn't routine first return Nil when no values match?

Ruby hash: return the first key value under which is not nil

Read string from a file return nil

Remove first character if match from string

How to check if a string matches multiple strings and return value based on match

Search a string using list elements for matches and return the match found

Regex return match and extended matches

Return value from another table that matches values from the first table

Remove certain character from string and return into an array

return nil vs return false in Ruby

I am trying to convert the "Return First recurring character in a string problem" from python to powershell

match format and return tokens from a string

Excel return position of the first partial string match in a table, then return position of the last partial string match in the table

How to return string from function to Ruby with CGO

How return a string from a ruby hash

trying to match first character of each regex matches

Return a String WITHOUT the first two characters with exceptions like if the first character is 'a' then return it

sscanf_s doesn't return first character of string

How I can control the first character in a string if this is a return "\r"?

Return true if input matches any string from web request output

How to Return Nil String in Go?

Converting String to URL return nil