ruby-带哈希键的访问数组

时间:2018-11-22 23:26:42

标签: ruby

我正在努力了解如何使用哈希键访问数组。在我的代码中,我创建了一个包含键和值的哈希。现在,我想在Car类中设置值。每当我尝试实例化Car时,该参数都期望使用Integer而不是String。

我遇到以下错误:TypeError (no implicit conversion of String into Integer)

这是我的代码:

class Car_maker

 attr_accessor :car_maker

 def initialize(car_maker)
  @car_maker = car_maker
 end

end

class Car_model < Car_maker

attr_accessor :km, :type, :transmission, :stock, :drivetrain, :status, 
:fuel, :car_maker, :model, :year, :trim, :features
#total number of instances & array with car objects
@@totalCars = 0
@@catalogue = []

def initialize(km, type, transmission, stock, drivetrain, status, fuel, car_maker, model, year, trim, features)
    super(car_maker)
    @km = km
    @type = type
    @transmission = transmission
    @stock = stock
    @drivetrain = drivetrain
    @status = status
    @fuel = fuel
    @model = model
    @year = year
    @trim = trim
    @features = features
    @@totalCars += 1
end 

def self.convertListings2Catalogue(line)
    #Initialise arrays and use them to compare
    type = ["Sedan", "coupe", "hatchback", "station", "SUV"]
    transmission = ["auto", "manual", "steptronic"]
    drivetrain = ["FWD", "RWD", "AWD"]
    status = ["new", "used"]
    car_maker = ["honda", "toyota", "mercedes", "bmw", "lexus"]
    hash = Hash.new

    #In this part, we hash the set of features using regex
    copyOfLine = line
    regex = Regexp.new(/{(.*?)}/)
    match_array = copyOfLine.scan(regex)

    match_array.each do |line|
        hash["features"] = line
    end

    #Now, we split every comma and start matching fields
    newStr = line[0...line.index('{')] + line[line.index('}')+1...line.length]
    arrayOfElements = newStr.split(',')

    arrayOfElements.each do |value|
        if value.include?("km") and !value.include?("/")
            hash["km"] = value
        elsif type.include?(value)
            hash["type"] = value
        elsif transmission.include?(value.downcase)
            hash["transmission"] = value
        elsif value.include?("/") and value.include?("km")
            hash["fuel economy"] = value
        elsif drivetrain.include?(value)
            hash["drivetrain"] = value
        elsif status.include?(value.downcase)
            hash["status"] = value
        elsif /(?=.*[a-zA-Z])(?=.*[0-9])/.match(value) and !value.include?("km")
            hash["stock"] = value
        elsif car_maker.include?(value.downcase)
            hash["carmaker"] = value
        elsif /^\d{4}$/.match(value)
            hash["year"] = value
        elsif value.length == 2
            hash["trim"] = value
        else
            if value.length > 2
                hash["model"] = value
            end
        end 
    end 
  end
 end

 textFile = File.open('cars.txt', 'r')
 textFile.each_line{|line|
   if line.length > 2
    result = Car_model.convertListings2Catalogue(line)
    puts "Hash: #{result}"

    carObj = Car_model.new(result["km"], result["type"], result["transmission"], result["stock"], result["drivetrain"],
    result["status"], result["fuel"], result["carmaker"], result["model"], result["year"], result["trim"], result["features"])
    #@@catalogue.push (carObj)
end
}

1 个答案:

答案 0 :(得分:0)

此行

result = Car_model.convertListings2Catalogue(line)

不返回hash对象。它返回arrayOfElements,因为这实际上是each方法返回的结果,而each方法是该方法中执行的最后一个方法(尽管其中包含哈希分配,但这仅是最后一个值)返回,除非您使用显式的return语句。

只需在hash方法的最后一行中使用变量convertListing2Catalog

        if value.length > 2
          hash["model"] = value
        end
      end 
    end 
    hash # < this is the last line of the method so it's the value that will be returned
  end
end

考虑一下,该方法中创建了多个变量。没有理由期望会返回任何特定变量(例如hash)的内容,并且默认情况下,ruby方法会返回最后执行的命令。