Sunday, March 13, 2011

Ruby_Here_and_there_6-Using gsub for string replacement

This one is really good and simple. Liked the way ruby always simplifies things and makes it clear.

Traditional gsub using,

<pre class="code" lang="cpp">

irb(main):007:0> s="There is some thing about Mary"
=> "There is some thing about Mary"
irb(main):008:0> s.gsub("Mary", "MARY")
=> "There is some thing about MARY"
irb(main):009:0>

</pre>

Another way of using gsub

irb(main):005:0> s="There is some thing about Mary"
=> "There is some thing about Mary"
irb(main):006:0> s.gsub("Mary"){|c| c.upcase}
=> "There is some thing about MARY"
irb(main):007:0> 

No comments:

Post a Comment