From: Ryan Leavengood Date: 2005-12-21T06:58:50+09:00 Subject: Re: iterate chars in a string "Wrong" is a strong word, but I'd say this isn't ideal Ruby for two reasons: 1. Generally in Ruby internal iterators (i.e. each, each_byte, etc.) are preferred over external iterators like what you have here (and for and while loops.) 2. Your code isn't as efficient, though it wasn't as bad as I thought: ------------------------------------------------------------------------- | QuickBench Session Started | | 300 Iterations | ------------------------------------------------------------------------- user system total real 1. s.each_byte{|b| b.chr ... 2.656000 0.000000 2.656000 ( 2.669000) 2. 0.upto(s.length-1) { |... 2.859000 0.000000 2.859000 ( 2.887000) 3. s.split(//).each { |ch... 3.297000 0.000000 3.297000 ( 3.290000) 4. s.scan(/./m) { |charac... 7.594000 0.156000 7.750000 ( 7.776000) ------------------------------------------------------------------------- | Fastest was <1. s.each_byte{|b| b.chr ...> | ------------------------------------------------------------------------- The string s above was 4000 x characters. I was quite surprised the scan was so much slower, especially compared to split, which creates an array every time. Ryan On 12/20/05, Dirk Meijer wrote: > i've always used this: > > 0.upto(string.length-1) do |n| > p string[n,1] > end > > anything wrong with this? > greetings, Dirk.