Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

Donal Phipps
Donal Phipps
16,389 Points

each(&block) problem - Ruby examples - please help [SOLVED]

Hi, I've tried endlessly to fix this problem and finally gave in and need to ask for help, please.

When playing around with the first of the Ruby Examples for blocks, I get this error in the console:

:26: syntax error, unexpected $end, expecting ')' def each(%block)'

Here is my code

class Speech
    def initialize
        print "What is the speech name?"
        @title = gets.chomp
        @lines = []
        while add_line
            puts "Line added."
        end
    end

    def title
        @title
    end

    def add_line
        puts "Add a line: (blank line to exit)"
        line = gets.chomp
        if line.length > 0
            @lines.push line
            return line
        else
            return nil
        end
    end

    def each(%block)
        @lines.each { |line| yield line }
    end

end

speech = Speech.new
speech.each do |line|
    puts "[#{speech.title}] #{line}"
end

I've tried and tried to understand this. I know the error will be mine, but I can't figure it out. The line error suggests that the problem lies in the block for the each method, but it looks identical to the code given by Jason.

Can anyone help, please? Even just a clue will be very much appreciated.

2 Answers

Donal Phipps
Donal Phipps
16,389 Points

I'm going to leave this here so everyone can throw stones and point at me.

Line 26 - Correct % To &

I guess the way to learn is by being a complete idiot and getting the most basic mistakes out of the way as quickly as possible ...

On the plus side, I successfully shared my code in the forum post. Lots to be proud of today - go me!

Happy coding, all....

Marcus Tisäter
Marcus Tisäter
4,886 Points

It happens to a lot of us :) Don't worry, just don't rush next time and try look through you code one more time before posting the problem. Happy coding!

Donal Phipps
Donal Phipps
16,389 Points

Thanks - can't believe I did this! I went over it so many times... I learnt a lot about how to check your code from that one experience.

Have a good one.