Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Scooter D
9,611 PointsIteration with Regular Expression
Hey all, I have a quick question about some code in ruby I am learning.
Here is the code:
"This is a test".scan(/../) { |x| puts x }
In return I get:
1.9.3p392 :002 > "This is a test".scan(/../) { |x| puts x }
Th
is
i
s
a
te
st
This is what I expected. .scan is a method and is "scanning" through the string looking for matches from the original expression "This is a test" passed to it. In this case, the (/../) is looking for two letters at a time.
I don't quite understand the { |x| puts x } . What exactly is this? From reading I know that this is called a block and it is fed information, but I really don't know what that means? I supplemented "x" with y, c, and even the word number and got the same exact result as above. When I take out { |x| puts x } I get:
1.9.3p392 :006 > "This is a test".scan(/../)
=> ["Th", "is", " i", "s ", "a ", "te", "st"]
From what I know about Ruby so far, this looks like it is breaking the initial string "This is a test" into 2 letter individual strings. It is also not putting them on separate lines. So the { |x| puts x } may have something to do with creating a new line?
Any information would be greatly appreciated, thanks!
1 Answer
Jason Seifer
Treehouse Guest TeacherHey Scott,
Great question. It's not as complicated as you think. Check out the last line:
1.9.3p392 :006 > "This is a test".scan(/../)
=> ["Th", "is", " i", "s ", "a ", "te", "st"]
That's telling you that the return value of the scan statement is an array of two letter strings. When you pass the block to it, it's basically like calling the "each" method on that array. So the block will receive a string of two letters for each item in the array.
When you use the "puts" statement, that prints what you pass in to it as well as a new line. If you wanted to have it print out to the screen without the new line, you could use the "print" method.