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 S.’ it will supply ‘Derf Htims’
Here’s the code in full:
@fullname = fullname
#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 + " "
#just send back the single word
puts “Please enter your name:”
yourname = gets.chomp
jumbleyou = Jumbler.new(yourname)
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!