It is my first time to use Ruby to write something. Any suggestion is welcomed.
def largest_number(nums)
copy = nums.sort! {|a, b| b.to_s+a.to_s <=> a.to_s+b.to_s}
if copy[0] == 0
return "0"
end
copy.join('')
end
Your five lines in one :-P
def largest_number(nums)
nums.map(&:to_s).sort { |a, b| b + a <=> a + b }.join.to_i.to_s
end
Or:
def largest_number(nums)
nums.sort { |a, b| "#{b}#{a}" <=> "#{a}#{b}" }.join.to_i.to_s
end
Btw, copy = nums.sort!...
doesn't make sense. After that line, copy
and nums
refer to the exact same object. So you could just work with nums
. If you were trying to keep nums
intact (not sort it), you should remove the !
.