HWYDI: String splitting with exceptions August 22nd, 2008
the Problem
In an application I’m writing I’m parsing information from a Wiki and formatting it in XML. Some of the data I’m parsing needs to get split into an array, for example
"To Do: Update description, add more details (client, date, ...), categorize, publish" # Should become {"To Do" => ["Update description", "add more details (client, data, ...)", "categorize", "publish"]}
As you can guess the problem is the the commas between brackets. I can’t just split on commas because then I’d get [...(clients", "date", "...)" ...]
my Solution
Nothing yet, I tried something that looped over every char with a flag whether to split or not, but that (ofcourse) doesn’t work with a Regexp, so I’m back to square #1.
How would You do it?
l 4 comments »array x array? July 18th, 2008
Tom(warning: non-english blog) had a small friday-afternoon problem for me, which they couldn’t easily figure out. The problem:
x = [1, 2, 3] y = ['a', 'b', 'c'] ??? # result should == [[1,'a'],[2,'b'],[3,'c']]
My first guess was a simple * but apparently Array#* only takes strings and numbers:
x * 3 # => [1, 2, 3, 1, 2, 3, 1, 2, 3] x * '-' # => "1-2-3" x * y # => TypeError: can't convert Array into Integer
So I went through the Array API and found out there was something like transpose. Basically this is what you want:
x = [1, 2, 3] y = ['a', 'b', 'c'] result = [x,y].transpose # => [[1, "a"], [2, "b"], [3, "c"]]
update!
As Jean-Baptiste notes in the comments, there is also the zip function
[1, 2, 3].zip(['a', 'b', 'c']) # => [[1, "a"], [2, "b"], [3, "c"]]