0

I am trying to create a method that takes in a user input. It turns that user input into an integer, it then subtracts one from the user input. It also returns -1 if the user input is not a number. However the tests throws an error.enter image description here

  describe '#input_to_index' do

    it 'converts a user_input to an integer' do
      user_input = "1"

      expect(input_to_index(user_input)).to be_a(Fixnum)
    end

    it 'subtracts 1 from the user_input' do
      user_input = "6"

      expect(input_to_index(user_input)).to be(5)
    end

    it 'returns -1 for strings without integers' do
      user_input = "invalid"

      expect(input_to_index(user_input)).to be(-1)
    end

  end

Here is my method:

def input_to_index(user_input)
  user_input = user_input.to_i
  user_input = user_input - 1
  return -1 if !user_input.is_a? Numeric
end

2 Answers 2

3

It's because you're only returning something if !user_input.is_a?(Numeric) and you've already cast user_input to an integer.

-1 if false # => nil
-1 if true # => -1

So that last line in the method returns nil because the condition is never going to be met.

"a".to_i # => 0
"a".to_i.is_a?(Numeric) # => true
("a".to_i - 1).is_a?(Numeric) # => true

You don't even need that last line at all and things will work fine:

def input_to_index(user_input)
  user_input = user_input.to_i
  user_input = user_input - 1
end
input_to_index("1") # => 0
input_to_index("6") # => 5
input_to_index("invalid") # => -1

and more succinctly:

def input_to_index(user_input)
  user_input.to_i - 1
end
input_to_index("1") # => 0
input_to_index("6") # => 5
input_to_index("invalid") # => -1
Sign up to request clarification or add additional context in comments.

Comments

1

I'm sure there is a more eloquent way to do this, but you could do this:

def input_to_index(user_input)
  user_input = user_input.to_i
  user_input = user_input - 1
  if !user_input.is_a? Numeric
    -1
  else
    user_input
  end
end

EDIT

This might be a more eloquent way to do it:

def input_to_index(user_input)
  user_input = user_input.to_i - 1
  !user_input.is_a?(Numeric) ? -1 : user_input
end

Below is the most eloquent way to do that:

def input_to_index(user_input)
  user_input.to_i - 1
end

Credit: Simple Lime

2 Comments

After user_input = user_input.to_i, it is always an Integer, hence a Numeric. The if branch will thus never match. You are always going to the else branch.
What I wanted to say was that at the point where you check it, user_input can never be anything else than a Numeric. There is thus no point in checking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.