Question: Fake Binary: Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.
Can anyone explain why I got the error: ./lib/solution.rb:4:in `>': comparison of String with 5 failed (ArgumentError)
def fake_bin(s)
arr = s.split("")
arr.map! { |x| if x > 5 ? x = 1 : x = 0 }
return arr.join("")
end
I actually already completed the solution with gsub so I don't need other suggestions, I'm just curious why I couldn't get this approach to work and what has caused this error.
I did try framing the if statement in a variety of ways but it made no difference.
For
map
andmap!
it is important what the block returns, the assignment will not work.Then you got a bit of a mixture between a
if
and a ternary statement.Also you are comparing a string (input comes as a string, you
split
it into substrings) to an integer and this is where the error is coming from. Converting the string to an integer usingto_i
solves this problem.And lastly you do not need to return a value. Ruby has implicit retuns where the last value in a method is returned.
So something like this should work:
If you want to shorten it, you can skip the intermediate assignments and just chain all the calls: