Reputation: 79
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
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:
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 characterm
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 |
.gsub
, the string is rstrip
ped.Upvotes: 1
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
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