Last active
July 7, 2021 23:15
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://snap.hyuki.net/20210708075833/