I have to confess that I use a lot of Perl, and some of its idioms are
deeply embedded in my mind.
Im the course of parsing some data in Ruby I used a fragment of code
like
rules.each_line do |rule|
sku, price, special = rule.chomp.split(' ', 3)
# [...]
end
where rules was composed of lines of the form
A 50 3 for 130
coming from a perl background I would have expected ‘A’, ‘50’ and ‘3 for 130’
to have been assigned to sku, price and special. As it turned out
special had leading whitespace.
Maybe this is the difference Hal alludes to in From Perl to Ruby in his
book The Ruby Way: “Also, note that split also behaves slightly
differently.”
Is this intentional behaviour? I think that the Perl behaviour is more
useful (that is trimming the leading whitespace off the limit-th element
returned.)
In the perl debugger:
DB<1> $s = ’ A 50 3 for 130’
DB<2> @l = split(’ ', $s, 3)
DB<3> x @l
0 ‘A’
1 50
2 ‘3 for 130’
In irb:
’ A 50 3 for 130’.split(’ ', 3)
=> [“A”, “50”, " 3 for 130"]
What I’d like Ruby to do
’ A 50 3 for 130’.split(’ ', 3)
=> [“A”, “50”, “3 for 130”]
Mike
···
–
mike@stok.co.uk | The “`Stok’ disclaimers” apply.
http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA
mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60
http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA