Is there a better string.each?


(Tyler Spivey) #1

well, i have a bit of a problem:
a="canada"
a.each |i|
do something
end
and, it doesn’t loop over all the characters. is this normal? if so, how do i loop over all the characters?


(Dossy) #2

“canada”.split(//).each { |i| p i }

– Dossy

···

On 2002.07.05, Tyler Spivey tspivey8@telus.net wrote:

well, i have a bit of a problem:
a="canada"
a.each |i|
do something
end
and, it doesn’t loop over all the characters. is this normal? if so,
how do i loop over all the characters?


Dossy Shiobara mail: dossy@panoptic.com
Panoptic Computer Network web: http://www.panoptic.com/
“He realized the fastest way to change is to laugh at your own
folly – then you can let go and quickly move on.” (p. 70)


(Juergen Katins) #3

Hello

“Tyler Spivey” wrote:

well, i have a bit of a problem:
a="canada"
a.each |i|
do something
end
and, it doesn’t loop over all the characters. is this normal? if so, how
do i loop over all the characters?

String.each does not sepaerate each character (as one would normally assume)
but seperates
lines (by default, using the record seperator). Maybe it would have better
been named
string.each_record.
You can specify the seperator: str.each( aString=$/ )
example:

a="canada"
a.each(“a”) do |i|
p i
end

produces:

“ca”
“na”
“da”

Unfortunately you can not use string.each("") to seperate after each
character.

Juergen


(David Alan Black) #4

Hi –

···

On Fri, 5 Jul 2002, Dossy wrote:

On 2002.07.05, Tyler Spivey tspivey8@telus.net wrote:

well, i have a bit of a problem:
a="canada"
a.each |i|
do something
end
and, it doesn’t loop over all the characters. is this normal? if so,
how do i loop over all the characters?

“canada”.split(//).each { |i| p i }

There’s also String#each_byte, which will give you the numerical
character codes.

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav


(Austin Ziegler) #5

do i loop over all the characters?

String.each does not sepaerate each character (as one would
normally assume) but seperates lines (by default, using the record
seperator). Maybe it would have better been named
string.each_record. You can specify the seperator: str.each(
aString=$/ ) example:

[snip]

Unfortunately you can not use string.each("") to seperate after
each
character.

Is there any practical reason why $/ – or at least the argument to
string.each cannot be a regex? After all, it seems to me that ‘’ is
behaving like /\n+/m – and I personally find that Surprising, even
though it’s documented. I can understand perhaps why $/ might not be
best suited for regex handling, but why not allow at least the
argument to each either be string or regex?

-austin
– Austin Ziegler, austin@halostatue.ca on 2002.07.05 at 08.45.55

···

On Fri, 5 Jul 2002 15:56:27 +0900, Juergen Katins wrote: