# String, adding a numeric value to a part

**URL:** <https://www.ruby-forum.com/t/string-adding-a-numeric-value-to-a-part/147394>\
**Category:** Ruby\
**Created:** [September 1, 2008, 11:45am UTC](https://www.ruby-forum.com/t/string-adding-a-numeric-value-to-a-part/147394 "2008-09-01T11:45:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mayuresh\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/839c29/32.png) [@Mayuresh\_K](https://www.ruby-forum.com/u/Mayuresh_K)\
**Post date:** [September 1, 2008, 11:45am UTC](https://www.ruby-forum.com/t/string-adding-a-numeric-value-to-a-part/147394/1 "2008-09-01T11:45:04Z")

</div>

Hello,

Suppose there’s a variable called ‘a’ with a value = 1.  
Then I build a string “#{a} is really two”, which when printed gives  
“1 is really two”.  
How could I add a 1 to the a in that string to make it “2 is really  
two”?

Is there some way I could do something like “#{a}.to\_i + 1 is really  
two”?

Best,

---

<div class="post-metadata">

**Author:** ![Mayuresh\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/839c29/32.png) [@Mayuresh\_K](https://www.ruby-forum.com/u/Mayuresh_K)\
**Post date:** [September 1, 2008, 11:46am UTC](https://www.ruby-forum.com/t/string-adding-a-numeric-value-to-a-part/147394/2 "2008-09-01T11:46:41Z")

</div>

Mayuresh K. wrote:

> Hello,
> 
> Suppose there’s a variable called ‘a’ with a value = 1.  
> Then I build a string “#{a} is really two”, which when printed gives  
> “1 is really two”.  
> How could I add a 1 to the a in that string to make it “2 is really  
> two”?
> 
> Is there some way I could do something like “#{a}.to\_i + 1 is really  
> two”?
> 
> Best,

Inside #{} you can put whatever you want. “#{a+1} is really two”.

TPR.

---

<div class="post-metadata">

**Author:** ![Mayuresh\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/839c29/32.png) [@Mayuresh\_K](https://www.ruby-forum.com/u/Mayuresh_K)\
**Post date:** [September 1, 2008, 1:22pm UTC](https://www.ruby-forum.com/t/string-adding-a-numeric-value-to-a-part/147394/3 "2008-09-01T13:22:33Z")

</div>

2008/9/1 Thomas B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> > two"?
> > 
> > Best,
> 
> Inside #{} you can put whatever you want. “#{a+1} is really two”.

And if you want to modify the string _after_ evaluation you can do this:

irb(main):012:0\> s = “1 is really two”  
=\> “1 is really two”  
irb(main):013:0\> s.sub!(/\d+/) {|m| m.to\_i + 1}  
=\> “2 is really two”  
irb(main):014:0\> s  
=\> “2 is really two”

Or even

irb(main):005:0\> s = “1 is really two”  
=\> “1 is really two”  
irb(main):006:0\> s[/\d+/] = ($&.to\_i + 1).to\_s  
=\> “2”  
irb(main):007:0\> s  
=\> “2 is really two”

Kind regards

robert
