Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Ruby-tut] Easily creating strings
Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Sat Nov 13, 2004 1:05 am   Post subject: [Ruby-tut] Easily creating strings

In Ruby, we cannot simply add a number to a string and expect it to magically work. Something like:

code:
"hello " + 42


Simply doesn't work. We can explicitly turn 42 into a string, though, and then it will.

code:
"hello " + 42.to_s


But that takes a fair amount of work, and it just isn't natural.

So, we either need to make the first example work, or we need a better way to construct strings.

Don't hold your breath waiting for the latter. There are good reasons it won't work. However we do have a better way to construct strings.

code:
"hello #{42}"


This is known as string interpolation. Whatever is in the #{ } brackets is inserted into the string with an implied call to to_s.

Whatever you include? So... anything could be put in their?

Yep. Consider something like:

code:
"Hello, #{if true then "Mike" else "John" end}!"


The result of course is:

code:
"Hello, Mike!"
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: