O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variables, Methods, and Attributes

TestbedController is a pretty dull class so far. If you start Rails (with ruby script/server, the >> button in Heroku, or whatever does it in the environment you’ve installed), and visit http://localhost:3000/testbed/, you’ll get a mostly blank response. (In Heroku Garden, you may need to add testbed right after the URL that Heroku Garden sends you to when you've pressed >>.) There’s nothing in @result, because TestbedController’s index method doesn’t actually do anything.

That’s easily fixed. Change the definition of index to:

def index
   @result = 'hello'
end

Now, when you load the page, you’ll see “hello” as the result. (This is not exciting enough to deserve a screenshot.)

Variables

@result is a variable, a container for information. Because the name of the variable started with @, it is an instance variable, connected to the object in such a way that other objects can see it. That let the view retrieve it to shows its value. The new line of code assigned (=) an expression to the @result variable, the string hello.

The string was surrounded with single quotes (') to indicate that it was a string, a series of characters, rather than another variable name or something else entirely. If you need to include an apostrophe or single quote inside of a single-quoted string, just put a backslash (\) in front of the quote, as in 'Hello! Ain\'t it a pretty day?'. This is called escaping the quote, hiding it from normal processing.

Note

Ruby also lets you surround ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required