Felix
Felix

Reputation: 5619

Problems understanding Ruby code

I have this code:

all_backups = dir.entries[2..-1].sort.reverse
max_backups = 20
unwanted_backups = all_backups[max_backups..-1] || []

I think it gets all entries in a defined folder. What is [2..-1]? What is all_backups[max_backups..-1] || []?

Upvotes: 0

Views: 48

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

dir.entries[2..-1]

get elements from index 2(means 3rd element of your array) to last index(last element of your array). In Ruby -1 means last element of the Array instance.

all_backups[max_backups..-1] || []

all_backups[max_backups..-1] gives nil, then assign with an empty array [] to the variables other wise returned array from all_backups[max_backups..-1].

Upvotes: 1

Related Questions