I am working on a ruby module that matches the first item in a 2-dimentional array (imported from a csv file), and returns the second item. It sounds extremely simple, and I was able to get it to work, until I tried to match an item that wasn't in the array. When that happens, for some reason, the entire array is returned. I was able to rig a work-around, involving a boolian variable 'found', but I would like to know why this doesn't work as written.
require 'csv'
class Nutrition
@list = CSV.read("./lib/list.csv")
def self.carbs(name)
grams = @list.each do |item|
if item[0] == name
return item[1]
end
end
if grams == nil
grams = "error"
end
return grams
end
end
The list.csv file is as follows:
onion,13.75,0,0
carrot,11.375,0,0
cauliflower,19.375,0,0
cabbage,20.125,0,0
sw pepper,20,0,0
leek,7.5,0,0
mushroom,16.375,0,0
celery,33.25,0,0
apple,6.37,0,0
sweet potato,4.875,0,0
broccoli,14.8,0,0
red mill museli,1.52,0,0
mixed nuts,0,0,0.65
B. Sprouts,11,0,0
eggplant,16.66,0,0
quinoa,4.7,0,0
brown rice,4.33,0,0
sesame seed,0,0,4.5
sesame oil,0,0,4.655
pork chop,0,3.84,28.57
chick breast,0,3.22,27.77
lean turkey,0,4,100
ham,0,4.76,26.66
I edited my original code as follows:
require 'csv'
class Nutrition
include Enumerable
@list = CSV.read("./lib/list.csv")
def self.carbs(name)
result = @list.detect {|item| item|0| == name}
if result.nil?
result = "error"
end
result
end
end
Now, when I run rake test using the following testfile:
require './lib/nutrition.rb'
require "test/unit"
require 'csv'
class TestNutrition < Test::Unit::TestCase
include Enumerable
def test_carbs()
assert_equal(Nutrition.carbs('onion'), "13.75")
assert_equal(Nutrition.carbs('ham'),'0')
assert_equal(Nutrition.carbs('sawdust'), 'error')
end
end
I wind up with the following error message:
syntax error, unexpected == (SyntaxError) result = @list.detect {|item| item|0| == name} ^
However, when I run the following file, everything seems to work, I just can't seem to pass the rake test:
require 'csv'
class Nutrition
include Enumerable
@list = CSV.read("./lib/list.csv")
def self.carbs(name)
result = @list.detect {|item| item[0] == name}
if result.nil?
result = "error"
end
result
end
end
result = Nutrition.carbs('sawdust')
puts result