Ruby Array Ranges

(2011..1995).to_a 

returns an array

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

no. Why?

+4
source share
5 answers

to try

 > 2011.downto(1995).to_a => [2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995] 
+12
source

You can use this

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

+2
source

I do not see this working. 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> 
0
source

(1995.Time.now.year.to_i) .to_a works. The end must be more than the beginning.

0
source

I can not reproduce your results. Both of these expressions return an array.

Of course, since both ranges are empty, expressions always return an empty array, but this does not apply to your question.

0
source

Source: https://habr.com/ru/post/1339030/


All Articles