This code is the reason for your error
@allwords = @allwords + aword.reverse.capitalize + " "

Since @allwords has no value in it, by default that instance variable is
initialized to nil. Thus creating this error. You need to add @allwords =
"" before the loop.

 @allwords = ""
 @fullname.each do |aword|
        @allwords = @allwords + aword.reverse.capitalize + " "
 end

There is a simpler method to do the same thing
without initializing @allwords

return @fullname.map { |word| word.reverse.capitalize }.join(' ' )

the above could would yeild the same result.


On Wed, Feb 19, 2014 at 1:19 AM, Paul Robinson <lists / ruby-forum.com> wrote:

> Hello, I'm just setting out on Ruby and my first little program is
> generating an error (in the line @allwords = @allwords +
> aword.reverse.capitalize + " ")
>
> I'm trying to reverse a name, so it someone enters 'Fred' is will supply
> 'Derf' and if they enter 'Fred Smith' it will supply 'Derf Htims'
>
> Here's the code in full:
>
>
> class Jumbler
>   #attr_accessor :fullname
>   def initialize(fullname)
>     @fullname = fullname
>   end
>
>   def jumblename
>     #if there is more than one word, reverse each one
>     if @fullname.split(" ").length > 1
>       @fullname = @fullname.split(" ")
>       @fullname.each do |aword|
>         @allwords = @allwords + aword.reverse.capitalize + " "
>       end
>       return  @allwords
>     else
>       #just send back the single word
>       return @fullname.reverse.capitalize
>     end
>   end
> end
>
> puts "Please enter your name:"
> $stdout.flush
> yourname = gets.chomp
>
> jumbleyou = Jumbler.new(yourname)
> puts jumbleyou.jumblename
>
>
> I'm not sure if instance variables that are private to the object should
> appear in the initialization method (or whether they need to be denoted
> with '@' but that doesn't seen to fix the problem anyway). It seems to
> me that the error is because I'm trying to use 'reverse' or 'capitalize'
> on a 'nil' value but I can't see why that's happening.
>
> Guidance appreciated, sorry if my code is offensive! :D
>
> Paul
>
> --
> Posted via http://www.ruby-forum.com/.
>



-- 
Harisankar P S
https://twitter.com/coder_hsps | http://tech.hsps.in