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 ...
Get Learning Rails now with the O’Reilly learning platform.
O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.