Monday, November 13, 2006

Strange how string splitting is the same in Ruby, Python, and Perl, but maybe not?

Recently I wanted to have the individual characters of a string be assigned to left hand local variables. The string is always the same size, so after validating the size I wanted a single statement to assign values to local variables for each character within the string. Python was the most recent language I had spent time in, so I was reminded of the following:
>>> s = "12"
>>> a, b = s
>>> a
'1'
>>> b
'2'
>>>

This was exactly how I accomplished it before, so how about ruby. Let's try that in ruby using irb
irb(main):001:0> s = "12"
=> "12"
irb(main):002:0> a, b = s
=> ["12"]
irb(main):003:0> a
=> "12"
irb(main):004:0> b
=> nil
irb(main):005:0>

That is definetly not what I wanted. I thought so, how about perl?
$ perl -e '$s="12";($a,$b)=split("", $s);print "$a\n";print "$b\n"'
1
2

That works and looks like it would be close to the same in ruby I guess. Let's try:
irb(main):001:0> s = "12"
=> "12"
irb(main):002:0> s.split("")
=> ["1", "2"]
irb(main):003:0> a, b = s.split("")
=> ["1", "2"]
irb(main):004:0> a
=> "1"
irb(main):005:0> b
=> "2"
irb(main):006:0>

Now I have accomplished my original goal in ruby. Looking back I see python using an implicit action which wins for breavity, not that this was a competition. Ruby is close to that with an explicit action in an object esque, or message reciever way. Perl is explicit too, but dare I say a little harder to follow, and certainly not in a object esque syntax. It is amazing how close and far away the implementations are. As a final note Python's split does not allow the empty string, look at the ipython session below:
In [1]: "12".split("")
---------------------------------------------------------------------------
exceptions.ValueError Traceback (most recent call last)
/home/johnnyp/
ValueError: empty separator
In [2]:

Again because I had done a fair amount of python most recently I was surprised and expected the python behaviour a,b = "12" in ruby. This all led to asking on the ruby-talk mailing list. because I thought I might be missing some hidden ruby syntax. I initially used String#scan in my script and was quickly reminded of split from responses on the mailing list. Split more than likely can be found in your language of the day; However, be aware that it might miss behave ;-)

0 Comments:

Post a Comment

<< Home