Transcript ruby - Java
Ruby: An Introduction
• Created by Yukihiro Matsumoto in 1993
(named after his birthstone)
• Pure OO language (even the number 1 is an
instance of a class)
• Highly portable, works on Linux, UNIX,
DOS, Windows 95/98/NT/2K, Mac, etc.
Ruby: the Language
• Has garbage collection.
• Exception handling, like Java.
• Any class or instance can be extended
anytime (even during runtime)
• Allows operator overloading.
Ruby: the Language
• Can be extended with Ruby or low-level C.
• No type declaration.
• Has iterators, methods which accept blocks
for user-defined control structures (like
loops)
• Emacs, TextPad, and Vim all have support
available for Ruby.
Ruby
- To know ruby version, on command prompt:
ruby -v
- You can place a ruby program directly on the command line
using the -e option:
% ruby -e 'puts "hello world"'
hello world
- More conventionally, a ruby program can be stored in a file.
% echo "puts 'hello world'" > hello.rb
% ruby hello.rb
hello world
What is Irb?
- Interactive Ruby (IRb) provides a shell for
experimentation. Within the IRb shell, you
can immediately view expression results,
line by line.
- This tool comes along with Ruby installation
so you have nothing to do extra to have Irb
working.
- Just type irb at your command prompt and
an Interactive Ruby Session will start.
Reserved Keywords
Ruby Vs Java / C++
• Ruby
• C++ / Java
– “Ruby”.length
– strlen(“Ruby”);
– s.length();
– -5.0.abs
– abs(-5.0);
– number =
Math.abs(number);
Data Types
Ruby Arrays
Literals of Ruby Array are created by placing a commaseparated series of object references between square brackets.
A trailing comma is ignored.
ary = [ “abc", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
puts i
end
Result:
abc
10
3.14
This is a string
last element
Ruby Hashes
A literal Ruby Hash is created by placing a list of key/value
pairs between braces, with either a comma or the sequence =>
between the key and the value. A trailing comma is ignored.
Ruby Ranges
A Range represents an interval. A set of values with a start and an end. Ranges may be
constructed using the s..e and s...e literals, or with Range.new.
Ranges constructed using .. run from the start to the end inclusively. Those created using ...
exclude the end value. When used as an iterator, ranges return each value in the sequence.
A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 2, 3,
4 values.
Features
Free format - You can start writing your program from any line and column.
Case sensitive - Lowercase letters and uppercase letters are distinct. The keyword end, for example, is
completely different from the keyword END.
Comments - Anything following an unquoted #, to the end of the line on which it appears, is ignored by
the interpreter. Also, to facilitate large comment blocks, the ruby interpreter also ignores anything
between a line starting with =begin and another line starting with =end. This only works if the =
signs are the first characters of each line.
Statement delimiters - Multiple statements on one line must be separated by semicolons, but they are not
required at the end of a line; a linefeed is treated like a semicolon. If a line ends with a backslash (\),
the linefeed following it is ignored; this allows you to have a single logical line that spans several
lines.
Keywords- Also known as reserved words (around 41 of them) in Ruby typically cannot be used for other
purposes. You may be used to thinking that a false value may be represented as a zero, a null string, a
null character, or various other things. But in Ruby, all of these *values* are true; in fact, everything
is true except the reserved words false and nil. Keywords would be called "reserved words" in most
languages and they would never be allowed as identifiers. The Ruby parser is flexible and does not
complain if you prefix these keywords with @, @@ or $ prefixes and use them as instance, class or
global variable names. The best practice is to treat these keywords as reserved.
Strings
# p003rubystrings.rb
=begin
Ruby Strings
In Ruby, strings are mutable
=end
# Can use " or ' for Strings, but ' is more efficient
puts 'Hello World'
# String concatenation
puts 'I like' + ' Ruby'
# Escape sequence
puts 'It\'s my Ruby'
# New here, displays the string three times
puts 'Hello' * 3
# Defining a constant
PI = 3.1416
puts PI
#command using backticks
puts `dir`
- If puts is passed an object that is not a
string, puts calls the to_s method of that
object and prints the string returned by that
method.
- In Ruby, strings are mutable. They can
expand as needed, without using much time
and memory. Ruby stores a string as a
sequence of characters.
Variables and Constants
Variables
Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any
declarations. Variable name itself denotes its scope (local, global, instance, etc.).
A local variable (declared within an object) name consists of a lowercase letter (or an underscore)
followed by name characters (sunil, _z, hit_and_run).
An instance variable (declared within an object always "belongs to" whatever object self refers to) name
starts with an ''at'' sign (''@'') followed by a name (@sign, @_, @Counter).
A class variable (declared within a class) name starts with two ''at'' signs (''@@'') followed by a name
(@@sign, @@_, @@Counter). A class variable is shared among all objects of a class. Only one
copy of a particular class variable exists for a given class. Class variables used at the top level are
defined in Object and behave like global variables. Class variables are rarely used in Ruby
programs.
Global variables start with a dollar sign (''$'') followed by name characters. A global variable name can be
formed using ''$-'' followed by any single character ($counter, $COUNTER, $-x). Ruby defines a
number of global variables that include other punctuation characters, such as $_ and $-K.
Constants
A constant name starts with an uppercase letter followed by name characters. Class names and module
names are constants, and follow the constant naming conventions. Examples: PI=3.1416
Ruby Types
Ruby Pseudo Variables
Ruby Predefined Variables
Ruby: A Demonstration
#Person Class
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age.to_i
end
def inspect
"#@name (#@age)"
end
end
#Usage of the class
p1 = Person.new('elmo', 4)
p2 = Person.new('zoe', 7)
Advantages using Ruby
against Java and C++
• Support Regular Expression
• Cleaner code
– No need to declare variables
– Simple syntax (semi-colon is optional)
– Every thing is an object, even a number. No
need to call separate function.
– Simple object get/set methods declaration
Advantages (continue)
Better Access Control
– Dynamic access control
– Private methods never accessible directly by
another object
• Portable and extensible with third-party
library
• Interactive environment