Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Joseph Garcia
Joseph Garcia
8,312 Points

Need Help! " undefined local variable or method `item"

I am creating a ShoppingCart class , when the shopping cart is filled with 5 or more items it takes a 10 percent discount. I am having trouble on the prints_cart method of class.

class ShoppingCart attr_reader :name

def initialize(name)
    @name = name 
    @items = []

def add_items(item)

def total
    total = 0.0
    @items.each do |item|
        total += item.price 
    if @items.length < 5
    return total
else @items.length >= 5 
    return total - (total * 0.10)

def to_s 
    "Name: #{name}, Total: #{sprintf("%0.2f", total)}"

def print_cart
    puts "#{name}'s Shopping Cart"
    puts "-" * 40

    puts "Item".ljust(30) + "Price".rjust(10)
    add_items(item).each do |item|
        puts add_items.name.ljust(30) + sprintf("%0.2f", add_items.price).rjust(10)

    puts "-" * 40
    puts "Total:".ljust(30) + sprintf("%0.2f", total).rjust(10)
    puts "-" * 40


class Items def initialize(name, price) @name = name @price = price end end

banana = Items.new("Banana", 10) orange_juice = Items.new("Orange Juice" , 10) rice = Items.new("Rice", 1) vacuum_cleaner = Items.new("Vacuum Cleaner", 150) anchovies = Items.new("Anchovies" , 2) shopping_cart = ShoppingCart.new("Joseph") shopping_cart.add_items(banana) shopping_cart.add_items(orange_juice) shopping_cart.add_items(rice) shopping_cart.add_items(vacuum_cleaner) shopping_cart.add_items(anchovies) shopping_cart.print_cart

ClassAssignment.rb:34:in print_cart': undefined local variable or methoditem' for #<ShoppingCart:0x007febe1153928> (NameError) from ClassAssignment.rb:63:in `<main>'

Been stuck on it for hours :[ . I am a noob

1 Answer

David Axelrod
David Axelrod
36,073 Points

Hey Joseph!

Need a little bit of context! Where on treehouse do you have to make this shopping cart?