简体   繁体   中英

Ruby method unable to pass Rspec test

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. 在此处输入图片说明

  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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM