# Preserving Leading Zeros Using sprintf

**URL:** <https://www.ruby-forum.com/t/preserving-leading-zeros-using-sprintf/61752>\
**Category:** Ruby\
**Created:** [May 26, 2006, 9:54pm UTC](https://www.ruby-forum.com/t/preserving-leading-zeros-using-sprintf/61752 "2006-05-26T21:54:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jeremysarda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9e5f3/32.png) [@jeremysarda](https://www.ruby-forum.com/u/jeremysarda)\
**Post date:** [May 26, 2006, 9:54pm UTC](https://www.ruby-forum.com/t/preserving-leading-zeros-using-sprintf/61752/1 "2006-05-26T21:54:02Z")

</div>

From [http://www.rubycentral.com/ref/ref\_c\_array.html#collect\_oh:](http://www.rubycentral.com/ref/ref_c_array.html#collect_oh:)

“Invokes block once for each element of arr, replacing the element with  
the value returned by block.”

Okay, so I attempt to execute the following code:

a=3  
b=8  
[a,b].collect! { |c| c = sprintf(‘%02d’, c) }  
puts a # prints out 3 and not 03

However, this code:

a=3  
b=8  
(a,b) = [a,b].collect! { |c| c = sprintf(‘%02d’, c) }  
puts a # prints out 03

Why is that?

If it’s of any use, this is ruby 1.8.4 (2005-12-24) [i386-cygwin].

Thanks for demystification.

---

<div class="post-metadata">

**Author:** ![jeremysarda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9e5f3/32.png) [@jeremysarda](https://www.ruby-forum.com/u/jeremysarda)\
**Post date:** [May 26, 2006, 10:04pm UTC](https://www.ruby-forum.com/t/preserving-leading-zeros-using-sprintf/61752/2 "2006-05-26T22:04:32Z")

</div>

On 5/26/06, Jeremy S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> a=3  
> b=8  
> [a,b].collect! { |c| c = sprintf(‘%02d’, c) }  
> puts a # prints out 3 and not 03

You’ve been bit by the “variables == objects” mentality. When you  
perform your #collect!, each _element_ of the receiver of #collect! is  
replaced by the result of the yield. See this:

a = 3  
b = 8  
c = [a, b]  
c.collect! { |x| x = sprintf(‘%02d’, x) }  
puts c[0] # prints ‘03’

So when #collect! operates on the first element, it’s essentially as  
such:

c[0] = sprintf(‘%02d’, c[0])

This puts a _new_ object in that slot of the array; it _doesn’t_ alter  
the object that was previously in that slot. The variable a still  
refers to the old object, not the new one.

Jacob F.
