SlideShare a Scribd company logo
Let’s Code
Sameer Soni
@_sameersoni
–C.A.R. Hoare, The 1980 ACM Turing Award Lecture
“There are two ways of constructing a software
design: One way is to make it so simple that there
are obviously no deficiencies and the other way is to
make it so complicated that there are no obvious
deficiencies.”
– E. W. Dijkstra
“The computing scientist’s main challenge is not to
get confused by the complexities of his own
making.”
Kata
• is a Japanese word.
• are detailed choreographed patterns of
movements practised either solo or in
pairs.
• originally were teaching and training
methods by which successful combat
techniques were preserved and passed
on.
• Practicing kata allowed a company of
persons to engage in a struggle using a
systematic approach, rather than as
individuals in a disorderly manner.
• basic goal of kata is to preserve and
transmit proven techniques and to
practice self-defence.
• is a term used by some Software
Craftsmen, who write small snippets of
code to build muscle memory and
practise craft much like soldier, musician,
dancer or doctor.
- wiki
Ruby Functional Programming
Statement was incorrect until we were in school and
hadn’t been introduced to PROGRAMMING.
Expression is quite common in Imperative style of
programming.
But we don’t realise the side effects and pay heavy cost.
x = x + 1
Theory
Functional programming treats
computation as evolution of
mathematical functions and
avoids state and mutable data.
Promotes code with no side
effects, no change in value of
variables.
Discourages change of state.
Cleaner Code - Variables are not
modified once defined.
Referential transparency - Expressions
can be replaced by functions, as for
same input always gives same output.
Advantages
Benefits of RT:
1. Parallelization
2. Memoization
3. Modularization
4. Ease of debugging
Rules - Don’t update variables
No
• indexes = [1,2,3]
• indexes << 4
• indexes # [1,2,3,4]
Yes
• indexes = [1,2,3]
• all_indexes = indexes + [4] #[1,2,3,4]
Don’t append to arrays or strings
No
• hash = {a: 1, b: 2}
• hash[:c] = 3
• hash
Yes
• hash = {a: 1, b: 2}
• new_hash = hash.merge(c: 3)
Don’t update hashes
No
• string = “hello”
• string.gsub!(/l/, 'z')
• string # “hezzo
Yes
• string = "hello"
• new_string = string.gsub(/l/, 'z') # "hezzo"
Don’t use bang methods which modify in place
No
• number = gets
• number = number.to_i
Here, we are not updating number but overriding the old values,
which is as bad as updating.
Rule is: Once defined, its value should remain same in that scope
Yes
• number_string = gets
• number = number_string.to_i
Don’t reuse variables
Blocks as higher order functions
A block is an anonymous piece of code you can pass
around and execute at will.
No
• dogs = []
• ["milu", "rantanplan"].each do |name|
dogs << name.upcase
end
• dogs # => ["MILU", "RANTANPLAN"]
Yes
• dogs = ["milu", "rantanplan"].map do |name|
name.upcase
end # => ["MILU", "RANTANPLAN"]
init-empty + each + push = map
No
• dogs = []
• ["milu", "rantanplan"].each do |name|
if name.size == 4
dogs << name
end
end
• dogs # => [“milu"]
Yes
• dogs = ["milu", "rantanplan"].select do |name|
name.size == 4
end # => ["milu"]
init-empty + each + conditional push = select/reject
No
• length = 0
• ["milu", "rantanplan"].each do |dog_name|
length += dog_name.length
end
• length # 14
Yes
• length = ["milu", "rantanplan"].inject(0) do |accumulator, dog_name|
accumulator + dog_name.length
end # => 14
initialize + each + accumulate = inject
1st way:
hash = {}
input.each do |item|
hash[item] = process(item)
end
hash
How to create hash from an enumerable
2nd way:
Hash[input.map do |item|
[item, process(item)]
end]
input.inject({}) do |hash, item|
hash.merge(item => process(item))
end
# Way 1
if found_dog == our_dog
name = found_dog.name
message = "We found our dog #{name}!"
else
message = "No luck"
end
Everything is a expression
# Way 2
message = if (found_dog == my_dog)
name = found_dog.name
"We found our dog #{name}!"
else
"No luck"
end
Exercise
"What's the sum of the first 10 natural number
whose square value is divisible by 5?"
Ruby Functional way
Integer::natural.select { |x| x**2 % 5 == 0 }.take(10).inject(:+) #=> 275
Ruby Imperative way
n, num_elements, sum = 1, 0, 0
while num_elements < 10
if n**2 % 5 == 0
sum += n
num_elements += 1
end
n += 1
end
sum #=> 275
Source
• wikipedia.com
• code.google.com
Thanks

More Related Content

Similar to Let's Code

Programming in C by SONU KUMAR.pptx
Programming in C by SONU KUMAR.pptxProgramming in C by SONU KUMAR.pptx
Programming in C by SONU KUMAR.pptxSONU KUMAR
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basicsLuigi De Russis
 
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxOz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxALEJANDROLEONGOVEA
 
Python lab basics
Python lab basicsPython lab basics
Python lab basicsAbi_Kasi
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptxNileshBorkar12
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
Who go Types in my Systems Programing!
Who go Types in my Systems Programing!Who go Types in my Systems Programing!
Who go Types in my Systems Programing!Jared Roesch
 
Algorithm week2(technovation)
Algorithm week2(technovation)Algorithm week2(technovation)
Algorithm week2(technovation)than sare
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structuressonykhan3
 
Concept of Algorithm.pptx
Concept of Algorithm.pptxConcept of Algorithm.pptx
Concept of Algorithm.pptxElProfesor14
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_languageSINGH PROJECTS
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsAkhil Kaushik
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBasil Bibi
 
Unit 1 Introduction Part 3.pptx
Unit 1 Introduction Part 3.pptxUnit 1 Introduction Part 3.pptx
Unit 1 Introduction Part 3.pptxNishaRohit6
 

Similar to Let's Code (20)

Programming in C by SONU KUMAR.pptx
Programming in C by SONU KUMAR.pptxProgramming in C by SONU KUMAR.pptx
Programming in C by SONU KUMAR.pptx
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxOz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
c-programming
c-programmingc-programming
c-programming
 
Python programming
Python programmingPython programming
Python programming
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
Who go Types in my Systems Programing!
Who go Types in my Systems Programing!Who go Types in my Systems Programing!
Who go Types in my Systems Programing!
 
Algorithm week2(technovation)
Algorithm week2(technovation)Algorithm week2(technovation)
Algorithm week2(technovation)
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structures
 
Concept of Algorithm.pptx
Concept of Algorithm.pptxConcept of Algorithm.pptx
Concept of Algorithm.pptx
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_language
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & Algorithms
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
 
Unit 1 Introduction Part 3.pptx
Unit 1 Introduction Part 3.pptxUnit 1 Introduction Part 3.pptx
Unit 1 Introduction Part 3.pptx
 

Recently uploaded

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandIES VE
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAlluxio, Inc.
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke
 

Recently uploaded (20)

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

Let's Code

  • 2. –C.A.R. Hoare, The 1980 ACM Turing Award Lecture “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.”
  • 3. – E. W. Dijkstra “The computing scientist’s main challenge is not to get confused by the complexities of his own making.”
  • 4. Kata • is a Japanese word. • are detailed choreographed patterns of movements practised either solo or in pairs. • originally were teaching and training methods by which successful combat techniques were preserved and passed on. • Practicing kata allowed a company of persons to engage in a struggle using a systematic approach, rather than as individuals in a disorderly manner. • basic goal of kata is to preserve and transmit proven techniques and to practice self-defence. • is a term used by some Software Craftsmen, who write small snippets of code to build muscle memory and practise craft much like soldier, musician, dancer or doctor. - wiki
  • 5. Ruby Functional Programming Statement was incorrect until we were in school and hadn’t been introduced to PROGRAMMING. Expression is quite common in Imperative style of programming. But we don’t realise the side effects and pay heavy cost. x = x + 1
  • 6. Theory Functional programming treats computation as evolution of mathematical functions and avoids state and mutable data. Promotes code with no side effects, no change in value of variables. Discourages change of state. Cleaner Code - Variables are not modified once defined. Referential transparency - Expressions can be replaced by functions, as for same input always gives same output. Advantages Benefits of RT: 1. Parallelization 2. Memoization 3. Modularization 4. Ease of debugging
  • 7. Rules - Don’t update variables
  • 8. No • indexes = [1,2,3] • indexes << 4 • indexes # [1,2,3,4] Yes • indexes = [1,2,3] • all_indexes = indexes + [4] #[1,2,3,4] Don’t append to arrays or strings
  • 9. No • hash = {a: 1, b: 2} • hash[:c] = 3 • hash Yes • hash = {a: 1, b: 2} • new_hash = hash.merge(c: 3) Don’t update hashes
  • 10. No • string = “hello” • string.gsub!(/l/, 'z') • string # “hezzo Yes • string = "hello" • new_string = string.gsub(/l/, 'z') # "hezzo" Don’t use bang methods which modify in place
  • 11. No • number = gets • number = number.to_i Here, we are not updating number but overriding the old values, which is as bad as updating. Rule is: Once defined, its value should remain same in that scope Yes • number_string = gets • number = number_string.to_i Don’t reuse variables
  • 12. Blocks as higher order functions A block is an anonymous piece of code you can pass around and execute at will.
  • 13. No • dogs = [] • ["milu", "rantanplan"].each do |name| dogs << name.upcase end • dogs # => ["MILU", "RANTANPLAN"] Yes • dogs = ["milu", "rantanplan"].map do |name| name.upcase end # => ["MILU", "RANTANPLAN"] init-empty + each + push = map
  • 14. No • dogs = [] • ["milu", "rantanplan"].each do |name| if name.size == 4 dogs << name end end • dogs # => [“milu"] Yes • dogs = ["milu", "rantanplan"].select do |name| name.size == 4 end # => ["milu"] init-empty + each + conditional push = select/reject
  • 15. No • length = 0 • ["milu", "rantanplan"].each do |dog_name| length += dog_name.length end • length # 14 Yes • length = ["milu", "rantanplan"].inject(0) do |accumulator, dog_name| accumulator + dog_name.length end # => 14 initialize + each + accumulate = inject
  • 16. 1st way: hash = {} input.each do |item| hash[item] = process(item) end hash How to create hash from an enumerable 2nd way: Hash[input.map do |item| [item, process(item)] end] input.inject({}) do |hash, item| hash.merge(item => process(item)) end
  • 17. # Way 1 if found_dog == our_dog name = found_dog.name message = "We found our dog #{name}!" else message = "No luck" end Everything is a expression # Way 2 message = if (found_dog == my_dog) name = found_dog.name "We found our dog #{name}!" else "No luck" end
  • 18. Exercise "What's the sum of the first 10 natural number whose square value is divisible by 5?"
  • 19. Ruby Functional way Integer::natural.select { |x| x**2 % 5 == 0 }.take(10).inject(:+) #=> 275
  • 20. Ruby Imperative way n, num_elements, sum = 1, 0, 0 while num_elements < 10 if n**2 % 5 == 0 sum += n num_elements += 1 end n += 1 end sum #=> 275