5
(2011..1995).to_a 

returns an array

(Time.now.year.to_i..1995).to_a

doesn't. Why?

4
  • 1
    both of these statements return empty array for me. ruby 1.8.7p302 Commented Feb 9, 2011 at 13:55
  • Both return an empty array, as Eimantas says. However, if you you reverse the items in the range so that 1995 is first, they both return the expected array. Ranges aren't really meant going backwards. Commented Feb 9, 2011 at 14:44
  • you should indicate which Ruby version are you using Commented Feb 9, 2011 at 16:45
  • (Time.now.year.to_i).downto(1995).to_a Commented Apr 2, 2014 at 11:35

5 Answers 5

13

try

> 2011.downto(1995).to_a
=> [2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this

(Time.now.year.to_i).downto(1995).to_a

Comments

0

I don't see that either work. Here's irb on WinXP...

irb(main):009:0> (2011..1995).to_a
=> []
irb(main):010:0> (Time.now.year.to_i..1995).to_a
=> []
irb(main):011:0>

Comments

0

(1995..Time.now.year.to_i).to_a works. End should large than begin.

Comments

0

I cannot replicate your results. Both of these expressions return an array.

Of course, since both of the ranges are empty, the expressions will always return an empty array, but that's not relevant to your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.