SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Ruby 101
              Thomas Kjeldahl Nilsson
           thomas@kjeldahlnilsson.net
 linkedin.com/in/thomaskjeldahlnilsson
                   twitter.com/thomanil
“...we need to focus on humans,
on how humans care about doing
programming.”
                    -Yukihiro Matsumoto
What Are We
Covering Today?
                          bare basics
                           trying it out
  scripting, not system development
                      getting started!
Practical Info
Let’s Start!
Install
http://www.ruby-lang.org/en/downloads/
Run Code
   ruby -e 'puts 123'
     ruby myscript.rb
  or from your editor
Explore
      irb
        ri
Basic Syntax
Difference From
                                   Java, C#

No need for compilation
No casting, no type declarations
Dude.new(“Lebowski”) instead of new Dude(“Lebowski”)
nil instead of null
variable_name instead of variableName
can often skip semicolons and parens
Methods
def greet(name)
 puts("Hello, "+name);
end


def greet name
 puts "Hello, "+name
end


greet(“Mr Smith”);     => “Hello, Mr Smith”


greet “Mr Smith”       => “Hello, Mr Smith”
Variables


question = “Meaning of life?”


the_answer = 42
answer_alias = the_answer
answer_alias     => 42
Objects


“Some string”.methods => ["upcase!", "zip", "find_index" ...]
42.methods => ["%", "odd?", ... ]


Everything is an object.
Objects are easy to inspect.
Flow Control

if true
     puts “This is always true”
elsif false
   puts “This is always false”
else
  puts “This will never come to pass”
end
Flow Control



puts “Another way” if true


puts “This is never printed” unless false
EXERCISE 1
       courseware/exercises/1
Iterators and
                                              Blocks
5.times do
    puts “Nice for-loop, eh?”
end


5.times { puts “One-liner block form” }


(1..3).each do |n|
  puts “Say hello to number #{n}!”
end


[1,2,3].map do |n|
   n*2
end                     => [2, 4, 6]
EXERCISE 2
       courseware/exercises/2
Range


(1..5).to_a => [1, 2, 3, 4, 5]
(1...5).to_a => [1, 2, 3, 4]
numbers = 0..9
numbers.max                      => 9
numbers.min                      => 0
numbers.include? 5               => true
Array


an_array = [1, "two", 3, “four”] can have any types
an_array[0]      => 1
an_array[1..2] => [“two”, 3]
an_array.first => 1
an_array.last => “four”


“A short sentence”[2..6]       => “short”
EXERCISE 3
       courseware/exercises/3
String

holiday = “Christmas”
greeting = “Merry #{holiday}, everyone”


long_greeting = <<END_STRING
   This is a long unquoted string
   which includes line breaks, formatting, etc
   We can also interpolate: #{greeting}
END_STRING
EXERCISE 4
       courseware/exercises/4
Symbol

:there_can_be_only_one => :there_can_be_only_one


Evaluates to itself, unique
“Lonely enum value”
Hash


person = { "name" => "Tony S", :job => "waste management" }
person["name"] => "Tony S"
person[:job] => “waste management”
EXERCISE 5
       courseware/exercises/5
I/O
puts “What’s your name?”
typed_name = gets


file = File.new(“test.txt”, “r”)
#... do stuff to file
file.close


better way, use a block:
File.open(“test.txt”, “w”) do |file|
    file.puts “Writing a line, then closing it”
end
EXERCISE 6
       courseware/exercises/6
Environment


ARGV
ENV
EXERCISE 7
       courseware/exercises/7
Regular
                                    Expressions


“can you find me?” =~ /me/         => 12
$1                                 => “me”
“can you find this?” =~ /not there/ => nil
cat_name = “Felix”
“Felix loves milk” ” =~ /${cat_name}/ => 0
“Not here” !~ /Felix/                => true
Patterns
/^start of sentence/   anchor: start of sentence
/start of sentence$/   anchor: end of sentence
/[aeiou]/          match characters a,e,i,o or u
/[0-9]/            match any number between 0-9
/./                match any character except whitespace
/d/               match single digit (0-9)
/s/               match whitespace char
/d*/              match zero or more digits
/d+/              match one or more digits
/d{1,3}/          match number with length between 1 and 3
/d{3}/              match digit exactly 3 numbers long
/start (of the) sentence/ matches and captures (“of the”)
EXERCISE 8
       courseware/exercises/8
Shell Integration


`ls`   => <directory listing>
current_dir = `pwd`


file_path = “test.txt”
file_content = `pwd #{file_path}`
EXERCISE 9
       courseware/exercises/9
Filesystem
EXERCISE 10
       courseware/exercises/10
Your Turn!
EXERCISE 11
       courseware/exercises/11
Wrapping Up
Huge Gaps!
what about classes, modules, etc etc?
                  no need for that yet
       got enough for basic scripting!
References &
Further Studies
Web Resources
   http://www.ruby-lang.org/en/
    http://www.rubyinside.com/
Contact Infothomas@kjeldahlnilsson.net
  linkedin.com/in/thomaskjeldahlnilsson
                    twitter.com/thomanil

Weitere ähnliche Inhalte

Was ist angesagt?

My sql presentation
My sql presentationMy sql presentation
My sql presentation
Nikhil Jain
 

Was ist angesagt? (6)

Programvba
ProgramvbaProgramvba
Programvba
 
07 php
07 php07 php
07 php
 
I Doubt That!
I Doubt That!I Doubt That!
I Doubt That!
 
Byte manipulation in ruby
Byte manipulation in rubyByte manipulation in ruby
Byte manipulation in ruby
 
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
 

Andere mochten auch (11)

Ruby ile tanışma!
Ruby ile tanışma!Ruby ile tanışma!
Ruby ile tanışma!
 
Ruby 101 && Coding Dojo
Ruby 101 && Coding DojoRuby 101 && Coding Dojo
Ruby 101 && Coding Dojo
 
Ruby 101 session 5
Ruby 101 session 5Ruby 101 session 5
Ruby 101 session 5
 
Ruby 101 session 1
Ruby 101 session 1Ruby 101 session 1
Ruby 101 session 1
 
Introduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on RailsIntroduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on Rails
 
Ruby 101 session 4
Ruby 101 session 4Ruby 101 session 4
Ruby 101 session 4
 
Ruby101
Ruby101Ruby101
Ruby101
 
Ruby 101 session 3
Ruby 101 session 3Ruby 101 session 3
Ruby 101 session 3
 
Ruby 101 session 2
Ruby 101 session 2Ruby 101 session 2
Ruby 101 session 2
 
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasCurso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticas
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
 

Ähnlich wie Ruby 101

Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
Kerry Buckley
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 

Ähnlich wie Ruby 101 (20)

Ruby
RubyRuby
Ruby
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Kürzlich hochgeladen (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Ruby 101

  • 1. Ruby 101 Thomas Kjeldahl Nilsson thomas@kjeldahlnilsson.net linkedin.com/in/thomaskjeldahlnilsson twitter.com/thomanil
  • 2. “...we need to focus on humans, on how humans care about doing programming.” -Yukihiro Matsumoto
  • 3. What Are We Covering Today? bare basics trying it out scripting, not system development getting started!
  • 7. Run Code ruby -e 'puts 123' ruby myscript.rb or from your editor
  • 8. Explore irb ri
  • 10. Difference From Java, C# No need for compilation No casting, no type declarations Dude.new(“Lebowski”) instead of new Dude(“Lebowski”) nil instead of null variable_name instead of variableName can often skip semicolons and parens
  • 11. Methods def greet(name) puts("Hello, "+name); end def greet name puts "Hello, "+name end greet(“Mr Smith”); => “Hello, Mr Smith” greet “Mr Smith” => “Hello, Mr Smith”
  • 12. Variables question = “Meaning of life?” the_answer = 42 answer_alias = the_answer answer_alias => 42
  • 13. Objects “Some string”.methods => ["upcase!", "zip", "find_index" ...] 42.methods => ["%", "odd?", ... ] Everything is an object. Objects are easy to inspect.
  • 14. Flow Control if true puts “This is always true” elsif false puts “This is always false” else puts “This will never come to pass” end
  • 15. Flow Control puts “Another way” if true puts “This is never printed” unless false
  • 16. EXERCISE 1 courseware/exercises/1
  • 17. Iterators and Blocks 5.times do puts “Nice for-loop, eh?” end 5.times { puts “One-liner block form” } (1..3).each do |n| puts “Say hello to number #{n}!” end [1,2,3].map do |n| n*2 end => [2, 4, 6]
  • 18. EXERCISE 2 courseware/exercises/2
  • 19. Range (1..5).to_a => [1, 2, 3, 4, 5] (1...5).to_a => [1, 2, 3, 4] numbers = 0..9 numbers.max => 9 numbers.min => 0 numbers.include? 5 => true
  • 20. Array an_array = [1, "two", 3, “four”] can have any types an_array[0] => 1 an_array[1..2] => [“two”, 3] an_array.first => 1 an_array.last => “four” “A short sentence”[2..6] => “short”
  • 21. EXERCISE 3 courseware/exercises/3
  • 22. String holiday = “Christmas” greeting = “Merry #{holiday}, everyone” long_greeting = <<END_STRING This is a long unquoted string which includes line breaks, formatting, etc We can also interpolate: #{greeting} END_STRING
  • 23. EXERCISE 4 courseware/exercises/4
  • 24. Symbol :there_can_be_only_one => :there_can_be_only_one Evaluates to itself, unique “Lonely enum value”
  • 25. Hash person = { "name" => "Tony S", :job => "waste management" } person["name"] => "Tony S" person[:job] => “waste management”
  • 26. EXERCISE 5 courseware/exercises/5
  • 27. I/O puts “What’s your name?” typed_name = gets file = File.new(“test.txt”, “r”) #... do stuff to file file.close better way, use a block: File.open(“test.txt”, “w”) do |file| file.puts “Writing a line, then closing it” end
  • 28. EXERCISE 6 courseware/exercises/6
  • 30. EXERCISE 7 courseware/exercises/7
  • 31. Regular Expressions “can you find me?” =~ /me/ => 12 $1 => “me” “can you find this?” =~ /not there/ => nil cat_name = “Felix” “Felix loves milk” ” =~ /${cat_name}/ => 0 “Not here” !~ /Felix/ => true
  • 32. Patterns /^start of sentence/ anchor: start of sentence /start of sentence$/ anchor: end of sentence /[aeiou]/ match characters a,e,i,o or u /[0-9]/ match any number between 0-9 /./ match any character except whitespace /d/ match single digit (0-9) /s/ match whitespace char /d*/ match zero or more digits /d+/ match one or more digits /d{1,3}/ match number with length between 1 and 3 /d{3}/ match digit exactly 3 numbers long /start (of the) sentence/ matches and captures (“of the”)
  • 33. EXERCISE 8 courseware/exercises/8
  • 34. Shell Integration `ls` => <directory listing> current_dir = `pwd` file_path = “test.txt” file_content = `pwd #{file_path}`
  • 35. EXERCISE 9 courseware/exercises/9
  • 37. EXERCISE 10 courseware/exercises/10
  • 39. EXERCISE 11 courseware/exercises/11
  • 41. Huge Gaps! what about classes, modules, etc etc? no need for that yet got enough for basic scripting!
  • 43.
  • 44.
  • 45.
  • 46.
  • 47. Web Resources http://www.ruby-lang.org/en/ http://www.rubyinside.com/
  • 48. Contact Infothomas@kjeldahlnilsson.net linkedin.com/in/thomaskjeldahlnilsson twitter.com/thomanil

Hinweis der Redaktion

  1. First page\n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. First page\n