How can I properly fix this ruby file output?

Using this code format:

class Country
  CODE_TO_NAME = {
    :us => 'United States',
    :mx => 'Mexico',
    :fr => 'France',
    :gr => 'Germany'
  }

  def self.name(code)
    # Write some code here
  end
end

puts Country.name(ARGV.shift)

I want my code to run with output like this:

$ ruby country_name.rb
Code not specified
$ ruby country_name.rb ca
Not match
$ ruby country_name.rb us
United States
$ ruby country_name.rb mx
Mexico

How should I go about this?

3 answers

  • answered 2019-01-11 05:50 sawa

    First, name your code's path as country_name.rb. Then, define Country.name as:

    def self.name(code)
      case
      when code.nil? then "Code not specified"
      when name = CODE_TO_NAME[code.to_sym] then name
      else "Not match"
      end
    end
    

  • answered 2019-01-11 06:27 iGian

    Other option, checking for the code before calling the method:

    class Country
      # no changes here
    
      def self.name(code)
        return "Not found" unless CODE_TO_NAME.has_key? code
        CODE_TO_NAME[code]
      end
    end
    
    code = ARGV[0]
    abort("Code not specified") unless code
    puts Country.name(code.to_sym)
    

  • answered 2019-01-11 08:26 Jörg W Mittag

    So, there are three cases we need to care about:

    1. the user supplies no code
    2. the user supplies a code that is not in the database
    3. the user supplies a code that is in the database

    In the first case, ARGV.first will be nil. We can add a nil key to CODE_TO_NAME with the appropriate message.

    In the second case, indexing into CODE_TO_NAME will return the default value, so we can set the default to the appropriate message.

    In the third case, the code we get from the command line will be a String, not a Symbol, so if we change the keys in CODE_TO_NAME to Strings, we can index into CODE_TO_NAME directly without any conversions.

    #!/usr/bin/env ruby
    
    class Country
      CODE_TO_NAME = Hash.new('Not match').merge({
        'us' => 'United States',
        'mx' => 'Mexico',
        'fr' => 'France',
        'gr' => 'Germany', # BTW, the ISO-3166-1 alpha-2 code for Germany is 'de'
        nil  => 'Code not specified'
      }).freeze
    
      def self.name(code)
        CODE_TO_NAME[code]
      end
    end
    
    puts Country.name(ARGV.shift)