T
Timothy Byrd
Hi all,
I'm just beginning to "get" Ruby. (Coming from a mostly C/C++
background), and I have a question.
I want to rearrange some elements in an array. For a simple example,
given this:
a = %w(Ruby is useful C++ is very very useful)
b, c = a.partition {|w| w =~ /^v/}
then either of these commands seem to do what I want:
c.insert(c.index( c.find {|i| i =~ /^u/} ), b).flatten
or
c[c.index( c.find {|i| i =~ /^u/} ),0] = b
Yes, it works, but the nested calls to #index and #find seem ugly to
me. It seems there ought to be a cleaner way to get the index of the
first item matching the pattern. Or is there a more Ruby-like way to
do this?
Btw, the reason for this is that I want to generate a list of my CDs
off of my local CDDB database. But I want to sort artists like
"Loreena McKennitt" as "McKennitt, Loreena", so I'm going to put some
custom comments in the files, e.g. - "#SORT=McKennitt, Loreena" and
then use them in the ruby script that generates the list. According to
the CDDB standard, though, all comment lines for a record must precede
any lines with keywords, so I want to insert them in the middle.
Thanks,
-- Timothy
I'm just beginning to "get" Ruby. (Coming from a mostly C/C++
background), and I have a question.
I want to rearrange some elements in an array. For a simple example,
given this:
a = %w(Ruby is useful C++ is very very useful)
b, c = a.partition {|w| w =~ /^v/}
then either of these commands seem to do what I want:
c.insert(c.index( c.find {|i| i =~ /^u/} ), b).flatten
or
c[c.index( c.find {|i| i =~ /^u/} ),0] = b
Yes, it works, but the nested calls to #index and #find seem ugly to
me. It seems there ought to be a cleaner way to get the index of the
first item matching the pattern. Or is there a more Ruby-like way to
do this?
Btw, the reason for this is that I want to generate a list of my CDs
off of my local CDDB database. But I want to sort artists like
"Loreena McKennitt" as "McKennitt, Loreena", so I'm going to put some
custom comments in the files, e.g. - "#SORT=McKennitt, Loreena" and
then use them in the ruby script that generates the list. According to
the CDDB standard, though, all comment lines for a record must precede
any lines with keywords, so I want to insert them in the middle.
Thanks,
-- Timothy