So,my question was, Why am I getting NoMethodError
regarding sort
method in function next_bigger
when being called ?
Here's the code :
class String
def sort
self.chars.sort.join
end
end
def next_bigger n
s = n.to_s
return -1 if n <= 10 || s == s.sort.reverse #This line resulting NoMethodError
(2..n).each do |p|
x = (s[0...-(p)] + s[-(p)..-1].sort).to_i
return x if x > n
end
-1
end
p next_bigger 12
You're not getting the NoMethodError on the line you think you are. It's happening 2 lines later. The other place where you call sort.
x = (s[0...-(p)] + s[-(p)..-1].sort).to_i
If you index a range of a string outside it's bounds, you get nil
""[1..-1] #=> nil
You get NoMethodError because you're calling sort on that nil
.