Ruby Enumerable and string

August 27, 2010 Mike Gehard

Did you know that you can call map() and each() on a Ruby string? Do you know how they behave? I hope I’m not the only one that thought they understood it but was proven mistaken.

What would you expect the following code to do?

"hello".map{|char| "Char#{char}"  }

I thought it would return me an array with a bunch of “Char” where x is each letter in “hello”. Nope…it returns:

["Charhello"]

What would you expect the following code to do?

"hello".each{|char| puts "Char#{char}"}

Yeah I thought it would write out a bunch of puts statements “Char” where x is each letter in “hello”. Nope it prints:

Charhello

Ok so maybe my thoughts on strings being enumerable were a little off…I’ve been wrong before and will probably be wrong again.

What really threw me for a loop was that I can access the characters in a string by index:

"hello"[1]

returns

101

which is the ASCII representation of “e”.

So what is the moral of this story? Sometimes things aren’t as the seem at first glance. And sometimes you need to step back, fire up irb and see what really is happening.

Update: Thanks all for the responses below.

About the Author

Biography

Previous
Fast user switching with Devise
Fast user switching with Devise

Ever wondered how to login as another user within Devise? Recently we had a feature request that would pro...

Next
Managing your ey-cloud-recipes
Managing your ey-cloud-recipes

If you've recently forked the ey-cloud-recipes on GitHub and then had issues managing and deploying multipl...

×

Subscribe to our Newsletter

!
Thank you!
Error - something went wrong!