Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active Jul 7, 2021
Embed
What would you like to do?
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