ruby - access array with hash key
I am struggling to understand how I can access an array with a hash key. In my code, I create a hash with keys and values. Now, I want to set the values in a Car class. Whenever I try to instantiate the Car, the argument expects Integer and not a String.
I am getting the following error: TypeError (no implicit conversion of String into Integer)
Here is my code:
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
}
ruby
|
show 5 more comments
I am struggling to understand how I can access an array with a hash key. In my code, I create a hash with keys and values. Now, I want to set the values in a Car class. Whenever I try to instantiate the Car, the argument expects Integer and not a String.
I am getting the following error: TypeError (no implicit conversion of String into Integer)
Here is my code:
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
}
ruby
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
In the last lines, I am trying to create a car by callingCar_model.new(result["type"]....)
– mendy
Nov 22 '18 at 23:30
"type"is the key, but it expects an Integer sinceresultis an array. How can I fix this?
– mendy
Nov 22 '18 at 23:30
Sorry, but, what's the content ofresult?, as an example. Expected input, expected output.
– Sebastian Palma
Nov 22 '18 at 23:32
resultis a hash table with the following :{"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}
– mendy
Nov 22 '18 at 23:33
|
show 5 more comments
I am struggling to understand how I can access an array with a hash key. In my code, I create a hash with keys and values. Now, I want to set the values in a Car class. Whenever I try to instantiate the Car, the argument expects Integer and not a String.
I am getting the following error: TypeError (no implicit conversion of String into Integer)
Here is my code:
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
}
ruby
I am struggling to understand how I can access an array with a hash key. In my code, I create a hash with keys and values. Now, I want to set the values in a Car class. Whenever I try to instantiate the Car, the argument expects Integer and not a String.
I am getting the following error: TypeError (no implicit conversion of String into Integer)
Here is my code:
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
}
ruby
ruby
asked Nov 22 '18 at 23:26
mendymendy
358
358
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
In the last lines, I am trying to create a car by callingCar_model.new(result["type"]....)
– mendy
Nov 22 '18 at 23:30
"type"is the key, but it expects an Integer sinceresultis an array. How can I fix this?
– mendy
Nov 22 '18 at 23:30
Sorry, but, what's the content ofresult?, as an example. Expected input, expected output.
– Sebastian Palma
Nov 22 '18 at 23:32
resultis a hash table with the following :{"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}
– mendy
Nov 22 '18 at 23:33
|
show 5 more comments
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
In the last lines, I am trying to create a car by callingCar_model.new(result["type"]....)
– mendy
Nov 22 '18 at 23:30
"type"is the key, but it expects an Integer sinceresultis an array. How can I fix this?
– mendy
Nov 22 '18 at 23:30
Sorry, but, what's the content ofresult?, as an example. Expected input, expected output.
– Sebastian Palma
Nov 22 '18 at 23:32
resultis a hash table with the following :{"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}
– mendy
Nov 22 '18 at 23:33
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
In the last lines, I am trying to create a car by calling
Car_model.new(result["type"]....)– mendy
Nov 22 '18 at 23:30
In the last lines, I am trying to create a car by calling
Car_model.new(result["type"]....)– mendy
Nov 22 '18 at 23:30
"type" is the key, but it expects an Integer since result is an array. How can I fix this?– mendy
Nov 22 '18 at 23:30
"type" is the key, but it expects an Integer since result is an array. How can I fix this?– mendy
Nov 22 '18 at 23:30
Sorry, but, what's the content of
result?, as an example. Expected input, expected output.– Sebastian Palma
Nov 22 '18 at 23:32
Sorry, but, what's the content of
result?, as an example. Expected input, expected output.– Sebastian Palma
Nov 22 '18 at 23:32
result is a hash table with the following : {"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}– mendy
Nov 22 '18 at 23:33
result is a hash table with the following : {"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}– mendy
Nov 22 '18 at 23:33
|
show 5 more comments
1 Answer
1
active
oldest
votes
This line
result = Car_model.convertListings2Catalogue(line)
Doesn't return the hash object. It returns arrayOfElements since that's what the each method actually returns and the each method is the last method executed in the method (although there are hash assignments within it, it's only the last value that's returned unless you use an explicit return statement.
Just use the variable hash in the last line of the convertListing2Catalog method
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
If you think about it, there were several variables created in the method. There's no reason to expect that the contents of any specific variable such as hash would be returned, and ruby methods by default return the last executed command.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439055%2fruby-access-array-with-hash-key%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This line
result = Car_model.convertListings2Catalogue(line)
Doesn't return the hash object. It returns arrayOfElements since that's what the each method actually returns and the each method is the last method executed in the method (although there are hash assignments within it, it's only the last value that's returned unless you use an explicit return statement.
Just use the variable hash in the last line of the convertListing2Catalog method
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
If you think about it, there were several variables created in the method. There's no reason to expect that the contents of any specific variable such as hash would be returned, and ruby methods by default return the last executed command.
add a comment |
This line
result = Car_model.convertListings2Catalogue(line)
Doesn't return the hash object. It returns arrayOfElements since that's what the each method actually returns and the each method is the last method executed in the method (although there are hash assignments within it, it's only the last value that's returned unless you use an explicit return statement.
Just use the variable hash in the last line of the convertListing2Catalog method
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
If you think about it, there were several variables created in the method. There's no reason to expect that the contents of any specific variable such as hash would be returned, and ruby methods by default return the last executed command.
add a comment |
This line
result = Car_model.convertListings2Catalogue(line)
Doesn't return the hash object. It returns arrayOfElements since that's what the each method actually returns and the each method is the last method executed in the method (although there are hash assignments within it, it's only the last value that's returned unless you use an explicit return statement.
Just use the variable hash in the last line of the convertListing2Catalog method
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
If you think about it, there were several variables created in the method. There's no reason to expect that the contents of any specific variable such as hash would be returned, and ruby methods by default return the last executed command.
This line
result = Car_model.convertListings2Catalogue(line)
Doesn't return the hash object. It returns arrayOfElements since that's what the each method actually returns and the each method is the last method executed in the method (although there are hash assignments within it, it's only the last value that's returned unless you use an explicit return statement.
Just use the variable hash in the last line of the convertListing2Catalog method
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
If you think about it, there were several variables created in the method. There's no reason to expect that the contents of any specific variable such as hash would be returned, and ruby methods by default return the last executed command.
edited Nov 23 '18 at 1:24
answered Nov 23 '18 at 1:19
SteveTurczynSteveTurczyn
26.7k42738
26.7k42738
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439055%2fruby-access-array-with-hash-key%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What's the array, you're trying to access with a hash key? what's the key?
– Sebastian Palma
Nov 22 '18 at 23:28
In the last lines, I am trying to create a car by calling
Car_model.new(result["type"]....)– mendy
Nov 22 '18 at 23:30
"type"is the key, but it expects an Integer sinceresultis an array. How can I fix this?– mendy
Nov 22 '18 at 23:30
Sorry, but, what's the content of
result?, as an example. Expected input, expected output.– Sebastian Palma
Nov 22 '18 at 23:32
resultis a hash table with the following :{"features"=>["AC,Heated Seats,Heated Mirrors,Keyless Entry"], "km"=>"65101km", "type"=>"Sedan", "transmission"=>"Manual", "stock"=>"18131A", "drivetrain"=>"FWD", "status"=>"Used", "fuel economy"=>"5.5L/100km", "carmaker"=>"Toyota", "model"=>"camry", "trim"=>"SE", "year"=>"2010"}– mendy
Nov 22 '18 at 23:33