Re: undefined method `string'

From: Comfort E.

Why does this work:

puts soup.a

but adding .string a la:

puts soup.a.string

results in:
undefined method `string’ for nil:NilClass (NoMethodError) ??

This means that the return value of “soup.a” is nil. Nil is an object in
Ruby, so:
puts nil
passes a nil object to the ‘puts’ method. The ‘puts’ method calls the
‘to_s’ method on the argument(s) passed to it. Nil has a to_s method
(that returns an empty string), so all is well.

However, nil does not have a ‘string’ method, which is the error you are
getting. Perhaps you are confusing Ruby with another language, and
actually meant:
puts soup.a.to_s
?

Gavin K. wrote:

From: Comfort E.

Why does this work:

puts soup.a

but adding .string a la:

puts soup.a.string

results in:
undefined method `string’ for nil:NilClass (NoMethodError) ??

This means that the return value of “soup.a” is nil. Nil is an object in
Ruby, so:
puts nil
passes a nil object to the ‘puts’ method. The ‘puts’ method calls the
‘to_s’ method on the argument(s) passed to it. Nil has a to_s method
(that returns an empty string), so all is well.

However, nil does not have a ‘string’ method, which is the error you are
getting. Perhaps you are confusing Ruby with another language, and
actually meant:
puts soup.a.to_s
?

Perhaps, but soup.a gives me actual results other than nil. “.a” is a
rubyful_soup method.

//Hoping I explained that correctly.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs