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! While you're at it, check out some resources Treehouse students have shared here.

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

Ruby

Jordan Aldujaili
Jordan Aldujaili
5,852 Points

string is nil when i try to get the first character

So I'm trying to get the first character in a string using .first and [0]. I have tried some of the other ways to do it using the ruby docs, but im getting the same result. Im getting this error: NoMethodError (undefined method `[]' for nil:NilClass). Any ideas?

def to_h
    attributes.compact.merge(photo_url: photo.url, first_name: first_name, last_name: last_name, last_name_initial: last_name.first)
end

'last_name' is nil ONLY when I try to extract the first character. Without the first i get this :

first_name: "Lexie",
last_name: "Johnson",
last_name_initial: "Johnson"

1 Answer

Tim Knight
Tim Knight
28,888 Points

Jordan,

I wrote an article back in 2007 that I think might help you: Formatting Names Using Ruby

last_name = "Knight"
puts last_name[0,1]

By using [0,1] you're basically grabbing a substring starting at 0 (the beginning of the string) and going over one character.

Jordan Aldujaili
Jordan Aldujaili
5,852 Points

Hi Tim,

Thanks for your reply. Using [0,1] works, but only with the console, and so does .first and [0].. I am still getting the undefined method `[]' for nil:NilClass. So last_name is nil whenever I try to modify it. e.g last_name by itself outputs the last name 'Johnson', but last_name.downcase, i get nil for last_name. Any ideas why I am getting nil for last_name?

Tim Knight
Tim Knight
28,888 Points

Can you share a little more of your code where you're actually defining last_name? It might be able to help either myself or other members see what your issue is.