hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Principle Of List Surprise #

by why in inspect

Two array-related behaviors that took me off-guard this week.

Zsban Ambrus displayed this technique for ignoring a list assignment.

 >> x, (*), z = [:x, :y, :z]
 => [:x, :y, :z]
 >> x
 => :x
 >> z
 => :z

And Christian Neukirchen showed the spooky split that the array constructor function does.

 >> Array("foo\nbar")
 => ["foo\n", "bar"]
 >> $/ = ' '; Array( "i'm in your house" )
 => ["i'm ", "in ", "your ", "house"]
said on 10 Jan 2005 at 09:56
Not quite as expected:
 irb(main):001:0> x,(*),z = [1,2,3,4,5,6,7,8,9,10]
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 irb(main):002:0> x
 => 1
 irb(main):003:0> z
 => 3
said on 10 Jan 2005 at 11:59

That looks right. If you want to capture all remaining array elements, use an asterisk on the z variable:

 >> x,(*),*z = [1,2,3,4,5,6,7,8,9,10]
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >> z
 => [3, 4, 5, 6, 7, 8, 9, 10]

Comments are closed for this entry.