Ruby Basics Page
/*********************************************** * Image Thumbnail Viewer Script- © Dynamic Drive (www.dynamicdrive.com) * This notice must stay intact for legal use. * Visit http://www.dynamicdrive.com/ for full source code ***********************************************/
Ruby is a dynamic programming language that has recently gained some popularity, mainly due to Rails framework, which is for Ruby programming language. The beauty of Rails is that it lets to do web development in faster time. (At least according to the literature).Lets do a quick start by installing Ruby first; in subsequent posts, I would assume that you already have Ruby installed with all things in place. First things first, you can download Ruby Ruby Installer.
As I always, lets dive into sort of black box programming (by black box, i mean without actually understanding internals of Ruby). So I’ll start by writing a small program that converts centigrade to Fahrenheit. (I know, its trivial but i am guessing it should give you some idea). Things you must know before hand is, that Ruby is interpreted language. You can use Notepad (I use Notepad++) to create Ruby files, Ruby files end with *.rb extension. For clarity, Ruby is a programming language, There is no such thing as RUBY (there’s no full form as it isn’t an acronym).
c = gets; # note you can define this in one line print(”Enter a centigrade value to convert:”,c = gets”);
# or even shorter and more denser version print(”Enter a centigrade value to convert to F ——> “, gets.to_i * 9 / 5 ) + 32
# (haha, you can see that I am a java guy obviously as i am still doing semi colons)
f = (c.to_i * 9 / 5) + 32
print(”The result is –>”, f)
Let’s break the code down;
- print(), well prints a message (duh!)
- c = gets declares a variable (variable type need not be specified), gets will take the keyboard input (String type) and assign the value to c variable.
- # is how we write comments
- c.to_i is how we are calling a method on c (c is a type remember?), the parenthesis need not be specified (I hate this part and for clarity you should specify parenthesis), to_i as name suggests converts the to integer type.
- print(), prints a message along with the value of f
Well, save this file and call it something (any name would do), and get ready to see results. (It’s not rocket science to run this through believe me
).
Output :
There you go, we just made our first Ruby program!
More to follow, stay tuned guys!
Click here for Output of above !
Regards
Vyas, Anirudh