Zach
Zach

Reputation: 895

Recursion in Ruby isnt working like I think it should

I don't understand why this method isn't working. when I put in a value that should pass the if statement it doesn't work.

def getBase
    puts "What is the base URL for the test?"
    x = gets
    if (x.include? 'http://') && ((x.split('.').at(x.split('.').length - 1).length) == 3)
      return x
    else
      puts "That is in the incorrect format."
      puts "Please format your url like this"
      puts "http://example.com"
      getBase
    end
end

input 'http://test.com'

result: statement repeats and does not exit recursion

Upvotes: 0

Views: 100

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

If the purpose is to enforce correct URL format and/or make sure it's an HTTP URL, why don't you use a tool designed to do that? Ruby's URI class is your friend:

require 'uri'

URI.parse('http://foo.bar').is_a?(URI::HTTP)
=> true

URI.parse('ftp://foo.bar').is_a?(URI::HTTP)
=> false

URI.parse('file://foo.bar').is_a?(URI::HTTP)
=> false

URI.parse('foo.bar').is_a?(URI::HTTP)
=> false

I'd write the code more like this:

require 'uri'

def get_base
  loop do
    puts "What is the base URL for the test?"
    x = gets.chomp
    begin
      uri = URI.parse(x)
      return uri.to_s if uri.is_a?(URI::HTTP)
    rescue URI::InvalidURIError
    end
    puts "That is in the incorrect format."
    puts "Please format your URL like this:"
    puts
    puts "    http://example.com"
  end
end

puts "Got: #{ get_base() }"

Upvotes: 1

When you get input with gets it includes the newline \n at the end (from the user hitting return). So your x is actually "http://test.com\n".

To get rid of this use String#chomp:

x = gets.chomp

That should do it.

Upvotes: 2

Related Questions