String#scan returns a two-dimensional array

For example I have the following string:
str = “Hello world”

When I do something like this it returns a two-dimensional array:
str.scan(/Hello (.*)/) #[[“world”]]

I have to do the following to get the result as a string:
str.scan(/Hello (.*)/).flatten.first
IMO this is not efficient, how can I get the result with just the method
‘first’ instead of ‘flatten.first’?

In other words I want my results in a one dimensional array.

I’m sure I’m doing something wrong,. but I don’t know what. Anyone any

You mean like this?

$VERBOSE = true

str = “Hello world”

get first capture

str.slice(/Hello (.)/, 1) #=> “world”
str[/Hello (.
)/, 1] #=> “world”
/Hello (.)/.match(str)[1] #=> “world”
/Hello (.
)/ =~ str; $1 #=> “world”

one dimensional array

/(.) (.)/.match(str).captures #=> [“Hello”, “world”]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs