Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active July 7, 2021 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyuki/59713ece1b5c9edc036bfcee5b198481 to your computer and use it in GitHub Desktop.
Save hyuki/59713ece1b5c9edc036bfcee5b198481 to your computer and use it in GitHub Desktop.
How do you convert "Hello, **world**!" to "Hello, <b>world</b>!" in Ruby?
text = <<"EOD"
Lorem**ipsum**dolorsitamet,
con*secteturadipiscing**elit**,
**sed****do**eiusmod**temporincididunt
utlabore**etdoloremagnaaliqua.
EOD
html = <<"EOD"
Lorem<b>ipsum</b>dolorsitamet,
con*secteturadipiscing<b>elit</b>,
<b>sed</b><b>do</b>eiusmod<b>temporincididunt
utlabore</b>etdoloremagnaaliqua.
EOD
def bold1(s)
t = ''
while s.match(/\*\*(.+?)\*\*/m)
t += "#{$`}<b>#{$1}</b>"
s = $'
end
t + s
end
def bold2(s)
s.gsub(/\*\*(.+?)\*\*/m) do
"<b>#{$1}</b>"
end
end
puts bold1(text) == html #=> true
puts bold2(text) == html #=> true
@hyuki
Copy link
Author

hyuki commented Jul 7, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment