SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

เกมส์จับคู่
เกมส์จับคู่เกมส์จับคู่
เกมส์จับคู่Aeew Autaporn
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
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)Sylvain Hallé
 
Missilecommand
MissilecommandMissilecommand
MissilecommandSusan Gold
 
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] Ruslan Shevchenko
 
Functional Programming and Ruby
Functional Programming and RubyFunctional Programming and Ruby
Functional Programming and RubyPat Shaughnessy
 
C programming - String
C programming - StringC programming - String
C programming - StringAchyut Devkota
 
Week 6 java script loops
Week 6   java script loopsWeek 6   java script loops
Week 6 java script loopsbrianjihoonlee
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentationAliul Kadir Akib
 
함수형사고 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 CAbinaya B
 
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 || ...AAKASH KUMAR
 

What's hot (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 || ...
 

Viewers also liked

Web architecture pocket guide
Web architecture pocket guideWeb architecture pocket guide
Web architecture pocket guidemeroooo
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
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 @CygnismediaClark Davidson
 
Architecture of a Modern Web App
Architecture of a Modern Web AppArchitecture of a Modern Web App
Architecture of a Modern Web Appscothis
 

Viewers also liked (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
 

Similar to Ruby basics ||

Blocks and loops.pptx
Blocks and loops.pptxBlocks and loops.pptx
Blocks and loops.pptxsandeep kumar
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16Max Kleiner
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics modulemanikanta361
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxjkapardhi
 
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 arraysSyed Afaq Shah MACS CP
 
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 SmalltalkSerge Stinckwich
 
(6) collections algorithms
(6) collections algorithms(6) collections algorithms
(6) collections algorithmsNico Ludwig
 
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 javalet's go to study
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introductionASIT Education
 

Similar to 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
 

Recently uploaded

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 

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.