Ruby Question

4 views
Skip to first unread message

Kyle Sexton

unread,
Feb 3, 2012, 10:48:43 PM2/3/12
to Kansas City Ruby User Group
All,

I'm struggling with a hopefully simple problem in one of my programs.
Given an block of text that can be any length in size:

str =<<EOF
ebdcgfa
eadbcfg
dcbeagf
fecdbga
gfabecd
egabcdf
agdfebc
bdcegfa
abgcdef
ceagdfb
egbfdca
dbcgfea
EOF

I'd like to have the output be:

str1 = "1 ebdcgfa 2 eadbcfg 3 dcbeagf 4 fecdbga"
str2 = "5 gfabecd 6 egabcdf 7 agdfebc 8 bdcegfa"
str3 = "9 abgcdef 10 ceagdfb 11 egbfdca 12 dbcgfea"

Each new string variable will have a chunk of four links from the
input block, prefaced with the line number of the block. I don't need
str1, str2, str3 to be string type if some other type works better,
just a way to reference them in order. Input block size can range
from 0 to some large number, say 100000. What's a clean way to do
this? I considered dumping all of the original block into an array,
but I'm not sure if arrays are designed for manipulating that many
elements.

I feel like I'm missing something and this is probably easier than my
loops with counting iterators, but maybe not. :)

Thanks,
Kyle Sexton

Greg Hansen

unread,
Feb 14, 2012, 12:10:05 PM2/14/12
to kc...@googlegroups.com
Kylie,

Looks like this should work.

index = []
str.split("\n").each_with_index {|s,i| index << "#{i} #{s}"}
index.each_slice(4) {|s| p s}

Hope that helps.

Greg


--
You received this message because you are subscribed to the Google Groups "Kansas City Ruby User Group" group.
To post to this group, send email to kc...@googlegroups.com.
To unsubscribe from this group, send email to kcrug+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/kcrug?hl=en.


Andy Ogzewalla

unread,
Feb 14, 2012, 12:18:11 PM2/14/12
to kc...@googlegroups.com
If you are concerned about input size/memory usage/performance then it is probably best to do some "low-level" string manipulation with loops and counters like you are talking about.

On Fri, Feb 3, 2012 at 9:48 PM, Kyle Sexton <k...@mocker.org> wrote:
Reply all
Reply to author
Forward
0 new messages