[Ruby-tut] Hello, Ruby!
Author |
Message |
wtd
|
Posted: Fri Jun 25, 2004 7:55 pm Post subject: [Ruby-tut] Hello, Ruby! |
|
|
Everything in Ruby is an object.
No, really.
You may have used Java, and thought you were doing object-oriented programming, but Java is only partially object-oriented. There are still primitive values like int, float, double and such which aren't.
This is probably the best thing about Ruby, and it's one that warrants being mentioned upfront. That said, if you have little to no object-oriented programming experience, Ruby is still friendly.
Hello, Ruby!
code: | puts "Hello, Ruby!" |
Pretty simple. The puts method prints an object, followed by a newline, much like Java's System.out.println. Ruby's puts method is smarter, though. It will only add a newline if one isn't already included.
code: | puts "Hello, Ruby!\n" |
Would produce exactly the same output as the previous code example.
Additional methods exist as well:
code: | # this is a comment, by the way...
# print doesn't append any extra newlines
print "Hello, Ruby!\n"
# printf works like the function of the same name in C
printf "%s, %s!\n", "Hello", "Ruby" |
Friendly Ruby
Now, we can output a string. We next need a name from the user so Ruby can be friendly.
code: | puts "Hello, Ruby!"
print "I'm "
name = gets
puts "Ruby says, \"hello, #{name}\"" |
The first and second lines look familiar. The third line calls the gets method which reads a string from standard input and assigns it to the variable "name".
The fourth line is probably the most novel so far. In the string, #{name} indicates that the variable name should be inserted into the string. This construct is incredibly flexible, and this is only a trivial demonstration of what it can do. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
|
|