[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

subarray using [1,-1] returns nil.

Todd Burch

8/23/2007 11:03:00 PM

a = %w(a b c d e f g) ;
puts "a.length = #{a.length}" ;

b = a[1,-1] ;
puts "b.length = #{b.length}" ;

Why is array b nil after the subarray? I expect it to be equal to "a"
minus the first element.

Todd
--
Posted via http://www.ruby-....

3 Answers

Todd Burch

8/23/2007 11:14:00 PM

0

Todd Burch wrote:
> a = %w(a b c d e f g) ;
> puts "a.length = #{a.length}" ;
>
> b = a[1,-1] ;
> puts "b.length = #{b.length}" ;
>
> Why is array b nil after the subarray? I expect it to be equal to "a"
> minus the first element.
>
> Todd

I think I see the issue (the issue = my error). The "-1" is the last
element of the array, and the method is epxecting a length, not an
element.

Todd
--
Posted via http://www.ruby-....

Nobuyoshi Nakada

8/23/2007 11:28:00 PM

0

Hi,

At Fri, 24 Aug 2007 08:14:15 +0900,
Todd Burch wrote in [ruby-talk:266016]:
> > a = %w(a b c d e f g) ;
> > puts "a.length = #{a.length}" ;
> >
> > b = a[1,-1] ;
> > puts "b.length = #{b.length}" ;
> >
> > Why is array b nil after the subarray? I expect it to be equal to "a"
> > minus the first element.
> >
> > Todd
>
> I think I see the issue (the issue = my error). The "-1" is the last
> element of the array, and the method is epxecting a length, not an
> element.

Maybe, don't you want to try a[1..-1]?

--
Nobu Nakada

Todd Burch

8/23/2007 11:56:00 PM

0

Nobuyoshi Nakada wrote:
> Hi,
>
> Maybe, don't you want to try a[1..-1]?

Very good! Works fantastic. Thanks!

I had coded b=a[1,a.length-1] but I like your solution better.

Todd
--
Posted via http://www.ruby-....