Zestyyy Zestyyy - 5 months ago 5
Ruby Question

Why does one method return an array while the other doesn't?

My first code looks like this:

def title(name)
string = []
name.split.each do |word|
string << word.capitalize
end
string.join(' ')
end

print title('bob doe')


This returns:

Bob Doe


My second code looks like this:

class Book
def title
@title
end

def title=(book_name)
@title = []
book_name.split.each do |word|
@title << word.capitalize
end
@title.join(' ')
end
end


The RSpec exercise I'm working on is asking me to capitalize whatever title it gives me. In this case, let's say they want

expect(@book.title).to eq("Inferno")


I guess my question is, how come the second code returns ["Inferno"] when the first code returned the results without the array?

I'm still quite new to programming, so thank you for any explanation!

Answer

title= does return the joined string, just like title does. But you're not using the return value of title=, you're using the value assigned to @title. @title.join('') returns the joined string, but it doesn't assign the joined string to @title. When title= exits, @title is still the array you constructed with the each.

Fix it like this:

class Book
  def title
    @title
  end

  def title=(book_name)
    @title = []
    book_name.split.each do |word|
      @title << word.capitalize
    end
    @title = @title.join(' ')
  end
end

Note that the return value of an assignment method normally doesn't matter, although it makes the most sense to return the assigned value, as the fixed method does.

Also note that experienced Rubyists would normally write those methods more succinctly:

class Book
  attr_reader :title

  def title=(book_name)
    @title = book_name.split.map(&:capitalize).join(' ')
  end
end

Presumably the tutorial you're following will eventually get around to the features of Ruby used in those versions of those methods.