GidB
GidB

Reputation: 45

`*': negative argument (ArgumentError) Ruby

I keep getting this negative argument error when running this code in the Codewars IDE. It runs fine in terminal but in Codewars it both passes the test and runs this error message simultaneously.

STDERR
main.rb:5:in `*': negative argument (ArgumentError)
    from main.rb:5:in `maskify'
    from main.rb:9:in `<main>'

The code is

def maskify(cc)
  x = cc.to_s
  y = "#" * (x.length - 4)
  return y + x.slice(-4..-1)
end

I'm new to Ruby but I've not heard anywhere that it has a problem with negative numbers being used in .slice. Am I missing something here? Thanks.

Upvotes: 1

Views: 1005

Answers (1)

Dmitry Barskov
Dmitry Barskov

Reputation: 1257

You're not considering cases when cc is shorter than 4 symbols.

And expression "#" * (x.length - 4) raises the error because you can't multiply a string by a negative number.

Try to use Array#max method to handle this:

"#" * [x.length - 4, 0].max

Upvotes: 2

Related Questions