Monday, September 20, 2010

Ruby- Basics

RUBY

Ruby is a programming language which is somewhat same as Python more complex than python. We can write a program and save it with an extension of 'filename.rb' and can run this program using 'ruby filename.rb'.

To write to the screen puts, print and printf are used.
PUTS- Write on the screen with a return at the end.
PRINT-Write on the screen without a return at the end.
PRINTF- I cant understand the main difference for printf from puts and print. i think printf is mainly used to print a floating point variables, strings etc.

To Read from the console we use gets
STDIN.gets-Standard input to the console is taken by the gets.
For example,
---------------------------------------
puts "What is your name?"
$name = STDIN.gets
puts "Hi "+$name
---------------------------------------

Functions

  We can define a method using def,
--------------------------------
def method_name(values)
    statements
end
-------------------------------
A method must end with 'end'. Indention has no importance here. end shows the ending of that method.

Uppercase- To make a string to upper case we can use upcase.
"hello".upcase => HELLO

To Return a value from a method 'return' is used. If return is not provided Ruby will return the contents of the last expression.
We can assign optional argument values and extra arguments to a method. Extra arguments are gathered into the last variable if preceded with a "*"
for example
--------------------------------
def test(a=1,b=2,*c)
   puts "#{a},#{b}"
   c.each{|x| print "#{x} "}
end
test 3,4,5,6,7,8,9
--------------------------------
which produces
-------------------------------
3,4
5,6,7,8,9
-------------------------------
If # is provided inside double quotes, #{variable} will evaluate the variable.

No comments:

Post a Comment