开发者

Find and replace variable in Ruby string

开发者 https://www.devze.com 2023-01-22 20:57 出处:网络
Let\'s say I have a string like so: \"Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator.\"

Let's say I have a string like so:

"Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."

I want to find all occurrences of [post]*[/post] and replace it with the title of the post represented by the number. I'd end up with somet开发者_如何学Gohing like so:

"Lorem ipsum de color Angry Turtle sit amet Fuzzy Rabit desectator."

I'm guessing a regex will be needed... looking for what the regex would be and how to use.


The gsub method on String has a handy block variation that works well here:

>> s = "Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."
=> "Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."

>> posts = {"57" => "Angry Turtle", "103" => "Fuzzy Rabit"}
=> {"57"=>"Angry Turtle", "103"=>"Fuzzy Rabit"}

>> s.gsub(/\[post\](\d+)\[\/post\]/) {|m| posts[$1] }
=> "Lorem ipsum de color Angry Turtle sit amet Fuzzy Rabit desectator."

Your syntax couldn't be much less regex friendly though. Try not to use brackets and slashes.


(after reading your easier syntax comment) If you have a hash like

posts = {57 => "Angry Turtle", 103 => "Fuzzy Rabit"}

or an array like, ehm,

posts = []
posts[57] = "Angry Turtle"
posts[103] = "Fuzzy Rabbit"

then why not go for string interpolation?

"Lorem ipsum de color #{posts[57]} sit amet #{posts[103]} desectator."

And you're ready to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消