Iggy Iggy - 6 months ago 9
Ruby Question

Perform method on each string separated by whitespace or hyphen

I am given a string and it can contain letters, whitespaces, and hyphens. Example:

str1 = "abcdef ghi-jkl"


I want to perform a method
method
on each word in
str1
(word here is a sequence of letters. It is delimited by a whitespace and/or hyphen).

For example, on
str1
:
method("abcdef")
,
method("ghi")
,
method("jkl")
will return
"abcdef* ghi*-jkl*"
(
*
is the outcome of each string method).
method ("abcdef ghi-jkl")
is not equal to (
method("abcdef")
method("ghi")
method("jkl")
). Whitespaces and hyphens will be returned to where they were originally.

How can I perform this?

My hunch is to use method combined with some sort of regex method.

Answer
def the_method(s)
  "[#{s}]"    # just an example
end

str1 = "abcdef ghi-jkl"
str1.gsub(/[^ -]+/) { |match| the_method(match) }
# or a bit shorter:
str1.gsub(/[^ -]+/, &method(:the_method))
# or a bit faster:
block = method(:the_method)
str1.gsub(/[^ -]+/, &block)

# all of those produce:
# => "[abcdef] [ghi]-[jkl]"
Comments