+ All Categories
Home > Technology > Ruby basics

Ruby basics

Date post: 16-Apr-2017
Category:
Upload: tushar-pal
View: 158 times
Download: 0 times
Share this document with a friend
45
Ruby (on Rails) Presented By Tushar Pal
Transcript
Page 1: Ruby basics

Ruby (on Rails)

Presented ByTushar Pal

Page 2: Ruby basics

About the Section

• Introduce the Ruby programming language• Basic understanding of ruby

Page 3: Ruby basics

What is Ruby?

• Programming Language• Object-oriented• Interpreted

Page 4: Ruby basics

Ruby Introduction

• Ruby originated in Japan during the mid-1990s

• Ruby is Based on Perl,Smalltalk,Eiffel,Ada and Lisp.

• Ruby offers automatic memory management.

• Ruby is Written in c

• Ruby is a dynamic interpreted language which has many strong features of various languages.

• It is a strong Object oriented programming language. Ruby is open source

• Ruby can be embeded into Hypertext Markup Language (HTML).

• Ruby has similar syntax to that of many programming languages such as C++ and Perl.

Page 5: Ruby basics

Interpreted Languages

• Not compiled like Java• Code is written and then directly executed by

an interpreter• Type commands into interpreter and see

immediate results

Computer

RuntimeEnvironmentCompilerCodeJava

:

ComputerInterpreterCodeRuby

:

Page 6: Ruby basics

What is Ruby on Rails (RoR)

• Development framework for web applications written in Ruby

• Used by some of your favorite sites!

Page 7: Ruby basics

Advantages of a framework

• Standard features/functionality are built-in• Predictable application organization

– Easier to maintain– Easier to get things going

Page 8: Ruby basics

Installation• Mac/Linux

– Probably already on your computer– OS X 10.4 ships with broken Ruby! Go here…

• http://hivelogic.com/articles/view/ruby-rails-mongrel-mysql-osx

Page 9: Ruby basics

RVMBefore any other step install mpapis public key (might need gpg2) (see

security)

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

\curl -sSL https://get.rvm.io | bash -s stable --ruby

Page 10: Ruby basics

hello_world.rb

puts "hello world!"

Page 11: Ruby basics

puts vs. print

• "puts" adds a new line after it is done – analogous System.out.println()

• "print" does not add a new line– analogous to System.out.print()

Page 12: Ruby basics

Running Ruby Programs

• Use the Ruby interpreterruby hello_world.rb

– “ruby” tells the computer to use the Ruby interpreter

• Interactive Ruby (irb) consoleirb

– Get immediate feedback– Test Ruby features

Page 13: Ruby basics

Comments# this is a single line comment

=beginthis is a multiline commentnothing in here will be part of the code

=end

Page 14: Ruby basics

Variables

• Declaration – No need to declare a "type"• Assignment – same as in Java• Example:

x = "hello world" # Stringy = 3 # Fixnumz = 4.5 # Floatr = 1..10 # Range

Page 15: Ruby basics

Objects

• Everything is an object. – Common Types (Classes): Numbers, Strings, Ranges– nil, Ruby's equivalent of null is also an object

• Uses "dot-notation" like Java objects• You can find the class of any variable

x = "hello"x.class → String

• You can find the methods of any variable or classx = "hello"x.methodsString.methods

Page 16: Ruby basics

Objects (cont.)

• There are many methods that all Objects have• Include the "?" in the method names, it is a

Ruby naming convention for boolean methods• nil?• eql?/equal?• ==, !=, ===• instance_of?• is_a?• to_s

Page 17: Ruby basics

Ruby defined? operators:

defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined.It returns a description string of the expression, or nil if the expression isn't defined.

There are various usage of defined? Operator:

Example

foo = 42defined? foo # => "local-variable"defined? $_ # => "global-variable"defined? bar # => nil (undefined)

Page 18: Ruby basics

Numbers

• Numbers are objects• Different Classes of Numbers

– FixNum, Float3.eql?2 → false-42.abs → 423.4.round → 33.6.rount→ 43.2.ceil → 43.8.floor → 33.zero? → false

Page 19: Ruby basics

String Methods"hello world".length → 11

"hello world".nil? → false

"".nil? → false

"ryan" > "kelly" → true

"hello_world!".instance_of?String → true

"hello" * 3 → "hellohellohello"

"hello" + " world" → "hello world"

"hello world".index("w") → 6

Page 20: Ruby basics

Operators and Logic

• Same as Java– Multiplication, division, addition, subtraction, etc.

• Also same as Java AND Python (WHA?!)– "and" and "or" as well as "&&" and "||"

• Strange things happen with Strings– String concatenation (+)– String multiplication (*)

• Case and Point: There are many ways to solve a problem in Ruby

Page 21: Ruby basics

if/elsif/else/end

• Must use "elsif" instead of "else if"• Notice use of "end". It replaces closing curly

braces in Java• Example:

if (age < 35)puts "young whipper-snapper"

elsif (age < 105)puts "80 is the new 30!"

elseputs "wow… gratz..."

end

Page 22: Ruby basics

Inline "if" statements

• Original if-statementif age < 105

puts "don't worry, you are still young"end

• Inline if-statementputs "don't worry, you are still young" if age < 105

Page 23: Ruby basics

for-loops

• for-loops can use ranges• Example 1:

for i in 1..10puts i

end

• Can also use blocks (covered next week)3.times do

puts "Ryan! "end

Page 24: Ruby basics

for-loops and ranges

• You may need a more advanced range for your for-loop

• Bounds of a range can be expressions• Example:

for i in 1..(2*5)puts i

end

Page 25: Ruby basics

while-loops

• Can also use blocks (next week)• Cannot use "i++"• Example:

i = 0while i < 5

puts ii = i + 1

end

Page 26: Ruby basics

unless

• "unless" is the logical opposite of "if"

• Example:unless (age >= 105) # if (age < 105)

puts "young."else

puts "old."end

Page 27: Ruby basics

until

• Similarly, "until" is the logical opposite of "while"

• Can specify a condition to have the loop stop (instead of continuing)

• Examplei = 0until (i >= 5) # while (i < 5), parenthesis not required

puts Ii = i + 1

end

Page 28: Ruby basics

Methods

• Structuredef method_name( parameter1, parameter2, …)

statementsend

• Simple Example:def print_ryan

puts "Ryan"end

Page 29: Ruby basics

Parameters

• No class/type required, just name them!• Example:

def cumulative_sum(num1, num2)sum = 0for i in num1..num2

sum = sum + iendreturn sum

end

# call the method and print the resultputs(cumulative_sum(1,5))

Page 30: Ruby basics

Return

• Ruby methods return the value of the last statement in the method, so…

def add(num1, num2)sum = num1 + num2return sum

end

can becomedef add(num1, num2)

num1 + num2end

Page 31: Ruby basics

User Input

• "gets" method obtains input from a user• Example

name = getsputs "hello " + name + "!"

• Use chomp to get rid of the extra lineputs "hello" + name.chomp + "!"

• chomp removes trailing new lines

Page 32: Ruby basics

Changing types

• You may want to treat a String a number or a number as a String

• to_i – converts to an integer (FixNum)• to_f – converts a String to a Float• to_s – converts a number to a String

• Examples"3.5".to_i → 3"3.5".to_f → 3.53.to_s → "3"

Page 33: Ruby basics

Constants

• In Ruby, constants begin with an Uppercase• They should be assigned a value at most once• This is why local variables begin with a

lowercase• Example:

Width = 5def square

puts ("*" * Width + "\n") * Widthend

Page 34: Ruby basics

Ruby Blocks

✓ You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly Ruby has a concept of Block.

✓ A block consists of chunks of code.

✓ You assign a name to a block.

✓ The code in the block is always enclosed within braces ({}).

✓ A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block.

✓ You invoke a block by using the yield statement.

Page 35: Ruby basics

Syntax:

block_name{ statement1 statement2 ..........}

Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.

Page 36: Ruby basics

The yield Statement:

Let us look at an example of the yield statement:

def test puts "You are in the method" yield puts "You are again back to the method" yieldendtest {puts "You are in the block"}

This will produce following result:

You are in the methodYou are in the blockYou are again back to the methodYou are in the block

Page 37: Ruby basics

You also can pass parameters with the yield statement. Here is an example:

def test yield 5 puts "You are in the method test" yield 100endtest {|i| puts "You are in the block #{i}"}

This will produce following result:

You are in the block 5You are in the method testYou are in the block 100

Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block.

Page 38: Ruby basics

Variables in a Ruby Class:

Ruby provides four types of variables:

1.Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _.

2.Instance Variables: Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name. 3. Class Variables: Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.

Page 39: Ruby basics

4.Global Variables: Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).

Variables in a Ruby Class:

Page 40: Ruby basics

Ruby Classes & Objects

class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" endend

# Create Objectscust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

Page 41: Ruby basics

Flow of Code# Call Methodscust1.display_details()cust1.total_no_of_customers()cust2.display_details()cust2.total_no_of_customers()

Customer id 1Customer name JohnCustomer address Wisdom Apartments, LudhiyaTotal number of customers: 1Customer id 2Customer name PoulCustomer address New Empire road, KhandalaTotal number of customers: 2

Page 42: Ruby basics

✓ Inheritance is a relation between two classes. ✓ Inheritance is indicated with <.

class Mammal    def breathe      puts "inhale and exhale"    end  end    class Cat < Mammal    def speak      puts "Meow"    end  end    rani = Cat.new  rani.breathe  rani.speak  

Inheritance

Page 43: Ruby basics

Features of Ruby

✓ Object-Oriented

✓ Portable

✓ Automatic Memory-Management (garbage collection)

✓ Easy And Clear Syntax

✓ Case Sensitive

Lowercase letters and uppercase letters are distinct. The keyword end, for example, is completely different from the keyword END. and features

Page 44: Ruby basics

✓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.

✓ Keywords

Also known as reserved words in Ruby typically cannot be used for other purposes.

A dynamic, open source programming language with a focus on simplicity and productivity

✓ Open Source

Page 45: Ruby basics

References

• Web Sites– http://www.ruby-lang.org/en/ – http://rubyonrails.org/

• Books– Programming Ruby: The Pragmatic Programmers'

Guide (http://www.rubycentral.com/book/)– Agile Web Development with Rails– Rails Recipes– Advanced Rails Recipes


Recommended