Noob question regarding strings

Hello,

I am still learning Ruby, my question is,

what is a string and what is a string literal? If possible, can you give
me an example of both. Any help would be much appreciated.

A string literal is anything in double quotes written in your program.

variable = “This is a string literal”

variable.class would return ‘String’, and so it’s a string. But it’s
not a litearl, it’s just a string. The literal is the “” side.

On Sun, Jan 1, 2012 at 9:57 PM, Linus P. [email protected] wrote:

Hello,

I am still learning Ruby, my question is,

what is a string and what is a string literal? If possible, can you give
me an example of both. Any help would be much appreciated.

First Google hit for “ruby doc string”
#=> http://ruby-doc.org/core-1.9.3/String.html

“… A String object holds and manipulates an
arbitrary sequence of bytes, typically representing characters. …”

A string literal is piece of code that is used to initialize a string:

E.g.

“this is a string literal”

so the line

s = “this is a string literal”

assigns the string literal (the part between " ") to the string s.

HTH,

Peter

Thank you Steve and Peter for answering my question, but I’m still
confused. Aren’t “variable” and “s” variables and not strings? They are
placeholders holding the string, which is the “” part right? I don’t see
where the literal is. :confused:

Thank you Bryan for answering the question. It helped.

Linus P. wrote in post #1039089:

Aren’t “variable” and “s” variables and not strings?

No as they do not reference another object. You can tell they are
strings because they are surrounded by double-quotes (").

They are placeholders holding the string, which is the “” part right?

Maybe this helps much?

string = "3"
=> "3"

"string"
=> "string"

I don’t see where the literal is. :confused:

The literal is just the string by itself:

"string" # this is a string literal

A regular string would be the string a variable references:

var = "string"
=> "string"    # this is the string referenced by `var`

"string"
=> "string" # this is just a string by itself, a string literal

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