Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

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. 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 strings with double quotes. Double-quoted strings offer a lot more escaping functionality, but single-quoted strings are ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata