m_antis
m_antis

Reputation: 79

How to remove a whitespace character and insert a string in its place

I'm trying to take a string such as Hello World this is Bob and have it formatted to

:h: :e: :l: :l: :o: | :w: :o: :r: :l: :d: | :t: :h: :i: :s: | :i: :s: | :b: :o: :b:

This is where I'm having the issue:

text = text.scan(/\s/).join(' | ')
def to_clipboard(text)
  string = text.to_s
  IO.popen('pbcopy', 'w') {|t| t << text}
  string
end
#########################################
print "Enter message: "

text = gets.downcase.chomp!
# text = text.scan(/\s/).join(' | ')
formatted = text.scan(/\S[A-Za-z]{0,0}/).join(': :')

formatted.insert(0,':')
formatted[formatted.size, 0] = ':'

# verify expected format
puts formatted

to_clipboard(formatted)

Upvotes: 0

Views: 186

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

I suggest

text = 'Hello World this is Bob'
p text.strip.gsub(/\s+|(\S)/) { |m| m == $~[1] ? ":#{$~[1].downcase}: " : '| ' }.rstrip
## => ":h: :e: :l: :l: :o: | :w: :o: :r: :l: :d: | :t: :h: :i: :s: | :i: :s: | :b: :o: :b:"

See the Ruby demo online.

NOTES:

  • The string is first stripped from leading/trailing whitespace in order not to add pipe at the start.
  • gsub(/\s+|(\S)/) { |m| m == $~[1] ? ":#{$~[1].downcase}: " : '| ' } does the main job within one regex replace pass:
    • /\s+|(\S)/ - matches 1+ whitespaces, or matches and captures into Group 1 any single non-whitespace character
    • The replacement is a block where m represents the match value. If the match value is equal Group 1 value (m == $~[1] ?) then the replacement is :, then Group 1 value in lower case (#{$~[1].downcase}), and then : , else, the replacement is | .
  • Since there may be a trailing space after gsub, the string is rstripped.

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

def bannerize(str)
  str.downcase.gsub(/./) do |c|
    if c == ' '
      "| "
    else
      ":#{c}: "
    end
  end.rstrip
end

bannerize("Hello this is Mugsy")
  #=> ":h: :e: :l: :l: :o: | :t: :h: :i: :s: | :i: :s: | :m: :u: :g: :s: :y:"

Alternatively,

def bannerize(str)
  h = Hash.new { |_,k| ":#{k}: " }.tap { |h| h[' '] = "| " }
  str.downcase.gsub(/./,h).rstrip
end

This uses the form of Hash::new that creates an empty hash h with a default proc, after which the key-value pair ' '=>" " is added to the hash so that it becomes { ' '=>" " }. The default proc causes h[k] to return ":#{k}: " if it does not have a key k; that is, if k is anything other than a space.

The form of String#gsub that employs a hash for making substitutions is then used with this hash h.

Upvotes: 2

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4329

Try to split by space, make a replacement in each word and then combine results:

words = text.split(/\s/)
words.map {|s| s.gsub(/(.)/, ':\1: ')}
formatted = words.join('| ')

Upvotes: 1

Related Questions