SlideShare ist ein Scribd-Unternehmen logo
1 von 62
Downloaden Sie, um offline zu lesen
Ruby
  ihower@gmail.com




    http://creativecommons.org/licenses/by-nc/2.5/tw/
?
•              a.k.a. ihower
    •   http://ihower.idv.tw/blog/

    •   http://twitter.com/ihower

•        2006                   Ruby
•          (    )      Rails Developer
    •   http://handlino.com

    •   http://registrano.com
?

•          a.k.a Ryudo
    • http://www.freebbs.tw
    • http://www.gameckub.tw
• 2007              Rails
• TOMLAN                    FOUNDER
Ruby?
•
    (interpreted)

•
•
•            Yukihiro Matsumoto, a.k.a. Matz
    •           Lisp, Perl,   Smalltalk

    •                                     Happy
•           Ruby 1.8.6 One-click Installer
• http://www.ruby-lang.org/en/downloads/
• Next -> Agree -> Enable Rubygems
Part1:
irb: Interactive Ruby

     irb(main):001:0>

     irb(main):001:0> 1 + 1
     => 2

     irb(main):002:0> 100 * 5 + 99
PUTS

•       notepad++         hello.rb
    puts "Hello World!"

•       ruby number.rb
Integer

5
-205
9999999999
0
Float
     .



54.321
0.001
-12.312
0.0
puts   1.0   +   2.0
puts   2.0   *   3.0
puts   5.0   -   8.0
puts   9.0   /   2.0

#   3.0
#   6.0
#   -3.0
#   4.5
puts     1   +   2
puts     2   *   3
puts     5   -   8
puts     9   /   2

#   3
#   6
#   -1
#   4
puts 5 * (12-8) + -15
puts 98 + (59872 / (13*8)) * -52
String

puts 'Hello, world!'
puts ''
puts 'Good-bye.'
puts 'I like ' + 'apple pie.'
puts 'You're smart!'

puts '12' + 12
#<TypeError: can't convert Fixnum into String>
Variable

composer = 'Mozart'
puts composer + ' was "da bomb", in his day.'

composer = 'Beethoven'
puts 'But I prefer ' + composer + ', personally.'
Conversions
var1 = 2
var2 = '5'

puts var1.to_s + var2 # 25
puts var1 + var2.to_i # 7

puts 9.to_f / 2 # 4.5
GETS
puts 'Hello there, and what's your name?'

name = gets.chomp

puts 'Your name is ' + name + '? What a lovely name!'
puts 'Pleased to meet you, ' + name + '. :)'
Methods
•                      (Object)


•          .
•                                 self
    puts   self.puts
var1 = 'stop'
var2 = 'foobar'
var3 = "aAbBcC"

puts   var1.reverse # 'pots'
puts   var2.length # 6
puts   var3.upcase
puts   var3.downcase
Flow Control
puts   1   > 2
puts   1   < 2
puts   5   >= 5
puts   5   <= 4
puts   1   == 1
puts   2   != 1

puts ( 2 > 1 ) && ( 2 > 3 ) # and
puts ( 2 > 1 ) || ( 2 > 3 ) # or
false     nil

puts "not execute" if nil
puts "not execute" if false

puts   "execute"   if   true #      execute
puts   "execute"   if   “” #     execute ( JavaScript   )
puts   "execute"   if   0 #     execute ( C     )
puts   "execute"   if   1 #     execute
puts   "execute"   if   "foo" #      execute
puts   "execute"   if   Array.new #      execute
puts "hello, who are you?"

name = gets.chomp

if name == "you"
     puts "that's you"
elsif name == "me"
     puts "that's me"
else
     puts "no ideas"
end
Case
case name
    when "John"
      puts "Howdy John!"
    when "Ryan"
      puts "Whatz up Ryan!"
    else
      puts "Hi #{name}!"
end
command = ''

while command != 'bye'
  puts command
  command = gets.chomp
end

puts 'Come again soon!'
Array
a = [ 1, "cat", 3.14 ]

puts a[0] #     1
puts a[1] #     “cat”
puts a.size #     3
colors = ["red", "blue"]

colors.push("black")
colors << "white"
puts colors.join(", ") # red, blue, black, white

colors.pop
puts colors.last #black
each method


languages = ['Ruby', 'Javascript', 'Perl']

languages.each do |lang|
  puts 'I love ' + lang + '!'
end

# I Love Ruby
# I Love Javascript
# I Love Perl
iterator
•     while                  each

     (iterator)
•   do .... end    each
             ( code block)
3.times do
  puts 'Good Job!'
end

# Good Job!
# Good Job!
# Good Job!
code block
                              closure

{ puts "Hello" } #    block

do
      puts "Blah" #   block
      puts "Blah"
end
code block
#
a = [ "a", "b", "c", "d" ]
b = a.map {|x| x + "!" }
puts b.inspect
#       ["a!", "b!", "c!", "d!"]

#
b = [1,2,3].find_all{ |x| x % 2 == 0 }
b.inspect
#       [2]
code block
file = File.new("testfile", "r")
# ...
file.close



File.open("testfile", "r") do |file|
    # ...
end
#
Hash
             (Associative Array)


config = { "foo" => 123, "bar" => 456 }

puts config["foo"] #     123
Symbols

config = { :foo => 123, :bar => 456 }

puts config[:foo] #     123
Methods
  def       end


def say_hello(name)
  result = "Hi, " + name
  return result
end

puts say_hello('ihower')
#     Hi, ihower
Methods
  def       end


def say_hello(name)
  result = "Hi, " + name
  return result
end

puts say_hello('ihower')
#     Hi, ihower
Person                          Class


                            Attributes     Methods




john = Person.new                                    mary = Person.new

                Object                                             Object


   Attributes     Methods                             Attributes     Methods
Classes
          new

color_string = String.new
color_string = "" #

color_array = Array.new
color_array = [] #

color_hash = Hash.new
color_hash = {} #

time = Time.new
puts time
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #{@name}"
      end

end

g1 = Greeter.new("ihower")
g2 = Greeter.new("ihover")

g1.say("Hello") #       Hello, ihower
g2.say("Hello") #       Hello, ihover
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #{@name}"
      end

end

g1 = Greeter.new("ihower")
g2 = Greeter.new("ihover")

g1.say("Hello") #       Hello, ihower
g2.say("Hello") #       Hello, ihover
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #{@name}"
      end

end

g1 = Greeter.new("ihower")
g2 = Greeter.new("ihover")

g1.say("Hello") #       Hello, ihower
g2.say("Hello") #       Hello, ihover
class Greeter

      def initialize(name)
          @name = name
      end
                                        (   )
      def say(word)
          puts "#{word}, #{@name}"
      end

end

g1 = Greeter.new("ihower")
g2 = Greeter.new("ihover")

g1.say("Hello") #       Hello, ihower
g2.say("Hello") #       Hello, ihover
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
attr_accessor, attr_writer, attr_reader

                                     class Person

class Person                           def name
                                         @name
  attr_accessor :name                  end

end                                    def name=(val)
                                        @name = val
                                       end

                                     end
Part2:
   gem install sinatra -y --no-ri --no-rdoc
  gem install nokogiri -y --no-ri --no-rdoc
RubyGems

• Ruby
• gem list
•            http://gemcutter.org/
Sinatra

•                     web development
• http://www.sinatrarb.com/
• gem install sinatra
web app
ruby myapp.rb                        http://localhost:4567


                # myapp.rb
                require 'rubygems'
                require 'sinatra'

                get '/' do
                  'Hello world!'
                end
URL
require 'rubygems'
require 'sinatra'

get '/hello/:name' do
    #     "GET /hello/foo"    "GET /hello/bar"
    # params[:name]       'foo'    'bar'
    "Hello #{params[:name]}!"
end
template
views             hello.erb


   # myapp.rb
   require 'rubygems'
   require 'sinatra'

   get '/hello/:name' do
     erb :hello
   end
ERB (Ruby Template)
 <!DOCTYPE html>
 <html>
 <head>
    <title>Sinatra app</title>
 </head>
 <body>
   <% 10.times do %>
     <p><%= "Hello #{params[:name]}!" %></p>
   <% end %>
 </body>
 </html>
Template
# myapp.rb
require 'rubygems'
require 'sinatra'

get '/array' do
    @arr = ["aaa","bbb","ccc","ddd"]
    erb :array
end


# views/array.erb
<% @arr.each do |item| %>
 <p><%= item %></p>
<% end %>
# myapp.rb          # views/index.erb
require 'rubygems'   <form action="/query" method="post">
require 'sinatra'
                        <p><input type="text" name="keyword" value=""></p>
get '/' do              <p><input type="submit" value="Submit"></p>
    erb :index
end                  </form>

post '/query' do
  params[:keyword]
end
nokogiri

• HTML, XML, SAX         (parser)
•      XPath     CSS
• gem install nokogiri
require 'rubygems'
require 'nokogiri'

text = "<html>
  <ul>
    <li>FOOOBARRR</li>
    <li>AAAAACCCCC</li>
  <ul>
</html>"

doc = Nokogiri::HTML(text)

puts doc.css('li').size # 2

doc.css('li').each do |item|
  puts item.content
end

# FOOOBARRR
# AAAAACCCCC
sinatra+nokogiri
   # myapp.rb
   require 'rubygems'
   require 'sinatra'
   require 'nokogiri'
   require 'open-uri'

   get '/' do
       erb :index
   end

   post '/query' do
     html = open( params[:keyword] ).read
     doc = Nokogiri::HTML(html)
     @links = doc.css('a')
     erb :query
   end
<!DOCTYPE html>
<html>
<head>
   	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul>
<% @links.each do |link| %>
     <li>
          <%= link.content %>
          <%= link.attributes["href"] %>
     </li>
<% end %>
</ul>

</body>
Thank you.




Learn to Program http://pine.fm/LearnToProgram/
Beginning Ruby 2nd. (Apress)

Weitere ähnliche Inhalte

Was ist angesagt?

Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13
Rafael Dohms
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
guestcf9240
 

Was ist angesagt? (20)

Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developers
 
Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Make Your Own Perl with Moops
Make Your Own Perl with MoopsMake Your Own Perl with Moops
Make Your Own Perl with Moops
 
There and Back Again
There and Back AgainThere and Back Again
There and Back Again
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
Perl 5.10
Perl 5.10Perl 5.10
Perl 5.10
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 

Ähnlich wie Ruby 入門 第一次就上手

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 

Ähnlich wie Ruby 入門 第一次就上手 (20)

An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby
RubyRuby
Ruby
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
 
Rails by example
Rails by exampleRails by example
Rails by example
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Getting Started with Microsoft Bot Framework
Getting Started with Microsoft Bot FrameworkGetting Started with Microsoft Bot Framework
Getting Started with Microsoft Bot Framework
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 

Mehr von Wen-Tien Chang

Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀
Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
Wen-Tien Chang
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
Wen-Tien Chang
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
Wen-Tien Chang
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
Wen-Tien Chang
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
Wen-Tien Chang
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
Wen-Tien Chang
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
Wen-Tien Chang
 

Mehr von Wen-Tien Chang (20)

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine Learning
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
 
Git Tutorial 教學
Git Tutorial 教學Git Tutorial 教學
Git Tutorial 教學
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 

Ruby 入門 第一次就上手

  • 1. Ruby ihower@gmail.com http://creativecommons.org/licenses/by-nc/2.5/tw/
  • 2. ? • a.k.a. ihower • http://ihower.idv.tw/blog/ • http://twitter.com/ihower • 2006 Ruby • ( ) Rails Developer • http://handlino.com • http://registrano.com
  • 3. ? • a.k.a Ryudo • http://www.freebbs.tw • http://www.gameckub.tw • 2007 Rails • TOMLAN FOUNDER
  • 4. Ruby? • (interpreted) • • • Yukihiro Matsumoto, a.k.a. Matz • Lisp, Perl, Smalltalk • Happy
  • 5. Ruby 1.8.6 One-click Installer • http://www.ruby-lang.org/en/downloads/ • Next -> Agree -> Enable Rubygems
  • 7. irb: Interactive Ruby irb(main):001:0> irb(main):001:0> 1 + 1 => 2 irb(main):002:0> 100 * 5 + 99
  • 8. PUTS • notepad++ hello.rb puts "Hello World!" • ruby number.rb
  • 10. Float . 54.321 0.001 -12.312 0.0
  • 11. puts 1.0 + 2.0 puts 2.0 * 3.0 puts 5.0 - 8.0 puts 9.0 / 2.0 # 3.0 # 6.0 # -3.0 # 4.5
  • 12. puts 1 + 2 puts 2 * 3 puts 5 - 8 puts 9 / 2 # 3 # 6 # -1 # 4
  • 13. puts 5 * (12-8) + -15 puts 98 + (59872 / (13*8)) * -52
  • 14. String puts 'Hello, world!' puts '' puts 'Good-bye.'
  • 15. puts 'I like ' + 'apple pie.' puts 'You're smart!' puts '12' + 12 #<TypeError: can't convert Fixnum into String>
  • 16. Variable composer = 'Mozart' puts composer + ' was "da bomb", in his day.' composer = 'Beethoven' puts 'But I prefer ' + composer + ', personally.'
  • 17. Conversions var1 = 2 var2 = '5' puts var1.to_s + var2 # 25 puts var1 + var2.to_i # 7 puts 9.to_f / 2 # 4.5
  • 18. GETS puts 'Hello there, and what's your name?' name = gets.chomp puts 'Your name is ' + name + '? What a lovely name!' puts 'Pleased to meet you, ' + name + '. :)'
  • 19. Methods • (Object) • . • self puts self.puts
  • 20. var1 = 'stop' var2 = 'foobar' var3 = "aAbBcC" puts var1.reverse # 'pots' puts var2.length # 6 puts var3.upcase puts var3.downcase
  • 22. puts 1 > 2 puts 1 < 2 puts 5 >= 5 puts 5 <= 4 puts 1 == 1 puts 2 != 1 puts ( 2 > 1 ) && ( 2 > 3 ) # and puts ( 2 > 1 ) || ( 2 > 3 ) # or
  • 23. false nil puts "not execute" if nil puts "not execute" if false puts "execute" if true # execute puts "execute" if “” # execute ( JavaScript ) puts "execute" if 0 # execute ( C ) puts "execute" if 1 # execute puts "execute" if "foo" # execute puts "execute" if Array.new # execute
  • 24. puts "hello, who are you?" name = gets.chomp if name == "you" puts "that's you" elsif name == "me" puts "that's me" else puts "no ideas" end
  • 25. Case case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!" end
  • 26. command = '' while command != 'bye' puts command command = gets.chomp end puts 'Come again soon!'
  • 27. Array a = [ 1, "cat", 3.14 ] puts a[0] # 1 puts a[1] # “cat” puts a.size # 3
  • 28. colors = ["red", "blue"] colors.push("black") colors << "white" puts colors.join(", ") # red, blue, black, white colors.pop puts colors.last #black
  • 29. each method languages = ['Ruby', 'Javascript', 'Perl'] languages.each do |lang| puts 'I love ' + lang + '!' end # I Love Ruby # I Love Javascript # I Love Perl
  • 30. iterator • while each (iterator) • do .... end each ( code block)
  • 31. 3.times do puts 'Good Job!' end # Good Job! # Good Job! # Good Job!
  • 32. code block closure { puts "Hello" } # block do puts "Blah" # block puts "Blah" end
  • 33. code block # a = [ "a", "b", "c", "d" ] b = a.map {|x| x + "!" } puts b.inspect # ["a!", "b!", "c!", "d!"] # b = [1,2,3].find_all{ |x| x % 2 == 0 } b.inspect # [2]
  • 34. code block file = File.new("testfile", "r") # ... file.close File.open("testfile", "r") do |file| # ... end #
  • 35. Hash (Associative Array) config = { "foo" => 123, "bar" => 456 } puts config["foo"] # 123
  • 36. Symbols config = { :foo => 123, :bar => 456 } puts config[:foo] # 123
  • 37. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  • 38. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  • 39. Person Class Attributes Methods john = Person.new mary = Person.new Object Object Attributes Methods Attributes Methods
  • 40. Classes new color_string = String.new color_string = "" # color_array = Array.new color_array = [] # color_hash = Hash.new color_hash = {} # time = Time.new puts time
  • 41. class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  • 42. class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  • 43. class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  • 44. class Greeter def initialize(name) @name = name end ( ) def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  • 45. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 46. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 47. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 48. attr_accessor, attr_writer, attr_reader class Person class Person def name @name attr_accessor :name end end def name=(val) @name = val end end
  • 49. Part2: gem install sinatra -y --no-ri --no-rdoc gem install nokogiri -y --no-ri --no-rdoc
  • 50. RubyGems • Ruby • gem list • http://gemcutter.org/
  • 51. Sinatra • web development • http://www.sinatrarb.com/ • gem install sinatra
  • 52. web app ruby myapp.rb http://localhost:4567 # myapp.rb require 'rubygems' require 'sinatra' get '/' do 'Hello world!' end
  • 53. URL require 'rubygems' require 'sinatra' get '/hello/:name' do # "GET /hello/foo" "GET /hello/bar" # params[:name] 'foo' 'bar' "Hello #{params[:name]}!" end
  • 54. template views hello.erb # myapp.rb require 'rubygems' require 'sinatra' get '/hello/:name' do erb :hello end
  • 55. ERB (Ruby Template) <!DOCTYPE html> <html> <head> <title>Sinatra app</title> </head> <body> <% 10.times do %> <p><%= "Hello #{params[:name]}!" %></p> <% end %> </body> </html>
  • 56. Template # myapp.rb require 'rubygems' require 'sinatra' get '/array' do @arr = ["aaa","bbb","ccc","ddd"] erb :array end # views/array.erb <% @arr.each do |item| %> <p><%= item %></p> <% end %>
  • 57. # myapp.rb # views/index.erb require 'rubygems' <form action="/query" method="post"> require 'sinatra' <p><input type="text" name="keyword" value=""></p> get '/' do <p><input type="submit" value="Submit"></p> erb :index end </form> post '/query' do params[:keyword] end
  • 58. nokogiri • HTML, XML, SAX (parser) • XPath CSS • gem install nokogiri
  • 59. require 'rubygems' require 'nokogiri' text = "<html> <ul> <li>FOOOBARRR</li> <li>AAAAACCCCC</li> <ul> </html>" doc = Nokogiri::HTML(text) puts doc.css('li').size # 2 doc.css('li').each do |item| puts item.content end # FOOOBARRR # AAAAACCCCC
  • 60. sinatra+nokogiri # myapp.rb require 'rubygems' require 'sinatra' require 'nokogiri' require 'open-uri' get '/' do erb :index end post '/query' do html = open( params[:keyword] ).read doc = Nokogiri::HTML(html) @links = doc.css('a') erb :query end
  • 61. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <ul> <% @links.each do |link| %> <li> <%= link.content %> <%= link.attributes["href"] %> </li> <% end %> </ul> </body>
  • 62. Thank you. Learn to Program http://pine.fm/LearnToProgram/ Beginning Ruby 2nd. (Apress)