Simple syntax question (models, validation)

who can explain this to me?

def before_validation
logger.info url
url = “http://” << url if url[0…3]==“www.”
end

the logger line correctly logs any URL that’s been submitted, let’s
say it’s “www.amazon.co.uk

BUT Rails raises an exception on the next line, complaining about nil.
[] (obviously from the url[0…3] bit)

It works if I replace that line with
self.url = “http://” << self.url if self.url[0…3]==“www.”

I just want an explanation why. It seems to be happy with logger.info
url, but why not url[0…3].

Why is ‘self.’ only necessary SOME of the time when manipulating model
attributes?

On 14 Jan 2008, at 14:14, AJS wrote:

BUT Rails raises an exception on the next line, complaining about nil.
[] (obviously from the url[0…3] bit)

It works if I replace that line with
self.url = “http://” << self.url if self.url[0…3]==“www.”

I just want an explanation why. It seems to be happy with logger.info
url, but why not url[0…3].

Well you always need self.url= if you want to set the value of url, if
not you are just setting a local variable.
When you write url you could either be referring to the local variable
url or trying to call the method url.
On the line logger.info url there is no local variable called url, so
its unambigious what you’re referring to.

But when you write url = “http://” << url if url[0…3]==“www.”
then a local variable called url is created (containing) nil. Now when
you say url ruby assumes you mean the local variable.
When local variables magic into existance is a slightly odd corner of
ruby.
For example, open up an irb prompt:

x #=> NameError: undefined local variable or method `x’ for main:Object
if false then x = 1; end #=> nil
x #=> nil

Fred

thanks - that’s tremendously helpful.

On Jan 14, 2:35 pm, Frederick C. [email protected]