Monday, 16 December 2019

How to sort the array of string by alphabetical order with domain based components in ruby?


Input:

array = ["analytics.ramo.com", "ccc.ramo.com", "ccc.test.ramo", "ddd.kumar.ramo.com", "ec2.new.ramo.com", "ramo.com", "test-new.ramo.com", "top-test.ramo.com"] 

Solution:

array.sort_by do |domain|
  parts = domain.split('.').reverse
  parts.unshift(parts.count)
end


Output:

["ramo.com",
 "analytics.ramo.com",
 "ccc.ramo.com",
 "test-new.ramo.com",
 "top-test.ramo.com",
 "ccc.test.ramo",
 "ddd.kumar.ramo.com",
 "ec2.new.ramo.com"]

No comments:

Post a Comment

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...