SlideShare uma empresa Scribd logo
1 de 19
RUBY BASICS - II
Abstract of
Session
 Loops
 Iterators & Blocks
 Array
 Hashes
 Iteration over Array and
Hashes
 Symbols

l19/12/11
Loops ?

Loops in Ruby are used to execute the same block of code a
specified number of times until some condition is met.

l19/12/11
While Loop
While loops will execute all of the statements contained within them as long as the
conditional statement remains true.
There are 3 ways to use while loop
Syntax :
1)

2)
3)

while condition do
code
end
code while condition
begin
code
end while condition

l19/12/11
Example

What is difference ?
In 2nd or 3rd case, code is executed once before conditional is evaluated.
example :
num = 0
max = 5
while num < max
puts("Inside the loop #{num}")
num += 1
end

l19/12/11
until

Executes code when condition is false.
There are 3 ways to use until loop
Syntax :
1) until condition do
code
end
2)
3)

code until condition
begin
code
end until condition

l19/12/11
For
Loop

lexample :
l

•for num in 0..5
puts("Inside the loop #{num}")
•end

lO/P :
•Inside the loop 0
•Inside the loop 1
•Inside the loop 2
•Inside the loop 3
•Inside the loop 4
•Inside the loop 5

l19/12/11
times

lexample :
l

• 5.times do |index|
puts("Inside the loop #{index}")
•end

lO/P :
•Inside the loop 0
•Inside the loop 1
•Inside the loop 2
•Inside the loop 3
•Inside the loop 4

l19/12/11
What are
iterators ?
l Another word for loop. In ruby, Iterators are nothing but methods supported by
collections.
l Objects that store a group of data members are called collections. In Ruby, arrays and
hashes can be termed collections.
l Iterators return all the elements of a collection, one after another. We will be discussing
two iterators here.
• each
• collect

l19/12/11
each

lSyntax :
•collection.each do |variable|
l
code
•end
lExample :

l

•num_array = [1,2,3,4,5]
•num_array.each do |num|
puts num
•end

lYou always associate the each iterator with a block. It returns each value of the
array, one by one, to the block. The value is stored in the variable num and then
displayed on the screen.

l19/12/11
collect

lThe collect iterator returns all the elements of a collection.
lSyntax :

•collection = collection.collect
lThe collect method need not always be associated with a block. The collect method
returns the entire collection, regardless of whether it is an array or a hash.

lexample :
•num_array = [1,2,3,4,5]
•new_array = num_array.collect{|num| 10*num}
•puts new_array

l19/12/11
What are
blocks?
lA block consists of chunks of code.
lYou assign a name to a block.
lThe code in the block is always enclosed within braces {}.
lA 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.
lYou invoke a block by using the yield statement.

l19/12/11
Blocks

lSyntax :
•block_name{
l
statement1
l
statement2
l
..........
•}
lExample :
•def test
l
puts "You are in the method"
l
yield
l
puts "You are again back to the method"
l
yield
•end
•test {puts "You are in the block"}

l19/12/11
Proc

Proc objects are blocks of code that have been bound to a set of local
variables.
Call a proc by using the variable’s call method
For Example :
p = Proc.new { |x, y, z| puts 100 * x + 10 * y + z }
p.call 14, 9, 2
=> 1492

l19/12/11
Arrays
 One array can contain any type of objects
 Grows automatically
l1) with the new class method:
nums = Array.new
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
l2) There is another method of Array, [].
nums = Array.[](1, 2, 3, 4,5)
OR
nums = Array[1, 2, 3, 4,5]

l19/12/11
Hashes

lA Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an
Array, except that indexing is done via arbitrary keys of any object type, not an integer
index.
lAs with arrays, there is a variety of ways to create hashes. You can create an empty hash
with the new class method:
lmonths = Hash.new
lExample:
•num = Hash["a" => 100, "b" => 200]
•keys = num.keys
•puts keys

l19/12/11
Questions ?
Thank You

Mais conteúdo relacionado

Mais procurados

เกมส์จับคู่
เกมส์จับคู่เกมส์จับคู่
เกมส์จับคู่
Aeew Autaporn
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Missilecommand
MissilecommandMissilecommand
Missilecommand
Susan Gold
 
Week 6 java script loops
Week 6   java script loopsWeek 6   java script loops
Week 6 java script loops
brianjihoonlee
 

Mais procurados (20)

เกมส์จับคู่
เกมส์จับคู่เกมส์จับคู่
เกมส์จับคู่
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
 
Loops in R
Loops in RLoops in R
Loops in R
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
 
Swift Study #3
Swift Study #3Swift Study #3
Swift Study #3
 
Missilecommand
MissilecommandMissilecommand
Missilecommand
 
C++ quik notes
C++ quik notesC++ quik notes
C++ quik notes
 
Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version] Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version]
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
String functions in C
String functions in CString functions in C
String functions in C
 
Chapter 5a -_array_-in_class-
Chapter 5a -_array_-in_class-Chapter 5a -_array_-in_class-
Chapter 5a -_array_-in_class-
 
Functional Programming and Ruby
Functional Programming and RubyFunctional Programming and Ruby
Functional Programming and Ruby
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Week 6 java script loops
Week 6   java script loopsWeek 6   java script loops
Week 6 java script loops
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in C
 
STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...
STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...
STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...
 

Destaque (8)

Rest in Rails
Rest in RailsRest in Rails
Rest in Rails
 
Web architecture pocket guide
Web architecture pocket guideWeb architecture pocket guide
Web architecture pocket guide
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Web Application Development Process presented by @Cygnismedia
Web Application Development Process presented by @CygnismediaWeb Application Development Process presented by @Cygnismedia
Web Application Development Process presented by @Cygnismedia
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Basic Web Concepts
Basic Web ConceptsBasic Web Concepts
Basic Web Concepts
 
Architecture of a Modern Web App
Architecture of a Modern Web AppArchitecture of a Modern Web App
Architecture of a Modern Web App
 

Semelhante a Ruby basics ||

Blocks and loops.pptx
Blocks and loops.pptxBlocks and loops.pptx
Blocks and loops.pptx
sandeep kumar
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
Serge Stinckwich
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
let's go to study
 

Semelhante a Ruby basics || (20)

Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
19 ruby iterators
19 ruby iterators19 ruby iterators
19 ruby iterators
 
Blocks and loops.pptx
Blocks and loops.pptxBlocks and loops.pptx
Blocks and loops.pptx
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
5 Statements and Control Structures
5 Statements and Control Structures5 Statements and Control Structures
5 Statements and Control Structures
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
 
Lecture 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arraysLecture 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arrays
 
Array and functions
Array and functionsArray and functions
Array and functions
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Arrays
ArraysArrays
Arrays
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
(6) collections algorithms
(6) collections algorithms(6) collections algorithms
(6) collections algorithms
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introduction
 
Imp_Points_Scala
Imp_Points_ScalaImp_Points_Scala
Imp_Points_Scala
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Último (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

Ruby basics ||

  • 2. Abstract of Session  Loops  Iterators & Blocks  Array  Hashes  Iteration over Array and Hashes  Symbols l19/12/11
  • 3. Loops ? Loops in Ruby are used to execute the same block of code a specified number of times until some condition is met. l19/12/11
  • 4. While Loop While loops will execute all of the statements contained within them as long as the conditional statement remains true. There are 3 ways to use while loop Syntax : 1) 2) 3) while condition do code end code while condition begin code end while condition l19/12/11
  • 5. Example What is difference ? In 2nd or 3rd case, code is executed once before conditional is evaluated. example : num = 0 max = 5 while num < max puts("Inside the loop #{num}") num += 1 end l19/12/11
  • 6. until Executes code when condition is false. There are 3 ways to use until loop Syntax : 1) until condition do code end 2) 3) code until condition begin code end until condition l19/12/11
  • 7. For Loop lexample : l •for num in 0..5 puts("Inside the loop #{num}") •end lO/P : •Inside the loop 0 •Inside the loop 1 •Inside the loop 2 •Inside the loop 3 •Inside the loop 4 •Inside the loop 5 l19/12/11
  • 8. times lexample : l • 5.times do |index| puts("Inside the loop #{index}") •end lO/P : •Inside the loop 0 •Inside the loop 1 •Inside the loop 2 •Inside the loop 3 •Inside the loop 4 l19/12/11
  • 9. What are iterators ? l Another word for loop. In ruby, Iterators are nothing but methods supported by collections. l Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections. l Iterators return all the elements of a collection, one after another. We will be discussing two iterators here. • each • collect l19/12/11
  • 10. each lSyntax : •collection.each do |variable| l code •end lExample : l •num_array = [1,2,3,4,5] •num_array.each do |num| puts num •end lYou always associate the each iterator with a block. It returns each value of the array, one by one, to the block. The value is stored in the variable num and then displayed on the screen. l19/12/11
  • 11. collect lThe collect iterator returns all the elements of a collection. lSyntax : •collection = collection.collect lThe collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash. lexample : •num_array = [1,2,3,4,5] •new_array = num_array.collect{|num| 10*num} •puts new_array l19/12/11
  • 12. What are blocks? lA block consists of chunks of code. lYou assign a name to a block. lThe code in the block is always enclosed within braces {}. lA 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. lYou invoke a block by using the yield statement. l19/12/11
  • 13. Blocks lSyntax : •block_name{ l statement1 l statement2 l .......... •} lExample : •def test l puts "You are in the method" l yield l puts "You are again back to the method" l yield •end •test {puts "You are in the block"} l19/12/11
  • 14. Proc Proc objects are blocks of code that have been bound to a set of local variables. Call a proc by using the variable’s call method For Example : p = Proc.new { |x, y, z| puts 100 * x + 10 * y + z } p.call 14, 9, 2 => 1492 l19/12/11
  • 15. Arrays  One array can contain any type of objects  Grows automatically l1) with the new class method: nums = Array.new nums = Array.new(10) { |e| e = e * 2 } puts "#{nums}" l2) There is another method of Array, []. nums = Array.[](1, 2, 3, 4,5) OR nums = Array[1, 2, 3, 4,5] l19/12/11
  • 16. Hashes lA Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. lAs with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method: lmonths = Hash.new lExample: •num = Hash["a" => 100, "b" => 200] •keys = num.keys •puts keys l19/12/11
  • 17.