Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to Ruby 张翼 [email protected] Friday, May 17, 13 Your Attention Please! This is a highly condensed presentation/course Friday, May 17, 13 Origination • Was first designed and developed in the mid-1990s by Yukihiro Matsumoto (松本行弘 (まつ もとゆきひろ) a.k.a. Matz in Japan • Got ideas from Perl, Lisp, Small talk, and etc. Friday, May 17, 13 Authoritative Resource • ruby-lang.org Friday, May 17, 13 Design Principles • Focus on human factors • Principle of Least Surprise • Principle of Succinctness Friday, May 17, 13 Principle of Least Surprise This principle is the supreme design goal of Ruby. It makes programers happy and makes ruby easy to learn. Examples: 1. What class is an object? o.class 2. Is it Array#size of Array#length? Either of the methods works. They re aliased 3. What are the different between arrays? diff = ary1 - ary2 union = ary1 + ary2 Friday, May 17, 13 Principle of Succinctness A.K.A. Principle of Least Effort • We don’t like to waste time on unnecessary code (xml config files, getters, setters, etc) • The quicker we program, the more we accomplish • Less code means less bugs Friday, May 17, 13 Main features • Everything is an object • Dynamic typing and Duck typing • Block • Reflective • Expressive • ... Friday, May 17, 13 irb - interactive ruby shell $ irb irb(main):001:0> puts "Hello, World" Hello, World => nil irb(main):002:0> 1+2 => 3 Friday, May 17, 13 Some fundamental datatypes • String • Symbol • Array • Hash Friday, May 17, 13 String ‘This is a simple Ruby string literal’ ‘Won\’t you read O\‘Reilly\’s book?’ “\t\”This quote begins with a tab and ends with a newline\”\n” greeting = “Hello” “#{greeting} World!” “Hi “ * 3 Friday, May 17, 13 # => “Hello World!” # => “Hi Hi Hi” Symbol :symbol :”symbol” :‘another long symbol’ str = “string” sym = str.to_sym str = sym.to_s Two strings may hold the same content and yet be completely distinct objects. But two strings with the same content will both convert to exactly the same Symbol object. Two distinct Symbol objects will always have different content. Friday, May 17, 13 Array a = [1, 'hi', 3.14, 1, 2, [4, 5]] puts puts puts puts Friday, May 17, 13 a[2] a.[](2) a.reverse a.flatten.uniq # # # # 3.14 3.14 [[4, 5], 2, 1, 3.14, 'hi', 1] [1, 'hi', 3.14, 2, 4, 5] Hash hash = Hash.new hash = { :water => 'wet', :fire => 'hot' } puts hash[:fire] # Prints: hot hash.each_pair do |key, value| # Or: puts "#{key} is #{value}" end # Prints: # hash.each do |key, value| water is wet fire is hot hash.delete :water # Deletes water: 'wet' hash.delete_if {|key,value| value=='hot'} # Deletes :fire => 'hot' Friday, May 17, 13 Classes class Person attr_reader :name, :age def initialize(name, age) @name, @age = name, age end def <=>(person) # Comparison operator for sorting age <=> person.age end def to_s "#{name} (#{age})" end end group = [ Person.new("Bob", 33), Person.new("Chris", 16), Person.new("Ash", 23) ] puts group.sort.reverse # => Bob (33) # => Ash (23) # => Chris (16) Friday, May 17, 13 Open classes class Person def <=>(person) name <=> person.name end end puts group.sort.reverse # => Chris (16) # => Bob (33) # => Ash (23) Friday, May 17, 13 Blocks and iterators (1) • Two syntaxes for creating a code block { puts “Hello World!” } # or begin puts “Hello World!” end Friday, May 17, 13 Blocks and iterators (2) 3.times { puts “thank you!” } data.each {|x| puts x} [1,2,3].map {|x| x*x } factorial = 1 2.upto(n) {|x| factorial *= x} In Ruby we use the term iterator to mean any method that uses the yield statement. They do not actually have to serve an iteration or looping function. Friday, May 17, 13 Blocks and iterators (3) Yielding the flow of program control to a block which was provided at calling time: def use_hello yield "hello" end # Invoke the above method, passing it a block. use_hello {|string| puts string} # => 'hello' Friday, May 17, 13 Blocks and iterators (4) A bit more complicated example: def reduce(array) if array.empty? nil else result = array.shift array.each do |item| result = yield result, item end result end end puts reduce([1, 2, 3, 4, 5]) {|a, b| a + b puts reduce([1, 2, 3, 4, 5]) {|a, b| a * b Friday, May 17, 13 } } # => 15 # => 120 Duck typing class Duck def quack puts "Quaaaaaack!" end def feathers puts "The duck has white and gray feathers." end end class Person def quack puts "The person imitates a duck." end def feathers puts "The person takes a feather from the ground and shows it." end end def in_the_forest(duck) duck.quack duck.feathers end def game donald = Duck.new john = Person.new in_the_forest donald in_the_forest john end game Friday, May 17, 13 Metaprogramming COLORS = { black: red: green: yellow: blue: magenta: cyan: white: "000", "f00", "0f0", "ff0", "00f", "f0f", "0ff", "fff" } class String COLORS.each do |color,code| define_method "in_#{color}" do "<span style=\"color: ##{code}\">#{self}</span>" end end end "Hello, World!".in_blue ==> "<span style==\"color: #00f\">Hello, World!</span>" Friday, May 17, 13 Method Missing class AttributeObject def initialize @attributes = {} end def method_missing(method, *args) str_method = method.to_s if str_method =~ /\=$/ str_method = str_method.sub(/\=$/, '') @attributes[str_method.to_sym] = args[0] else @attributes[method] end end end john = AttributeObject.new john.name = ‘John Conner’ john.age = 35 john.title = ‘UI designer’ puts john.name puts john.age puts john.title Friday, May 17, 13 # => ‘John Conner’ # => 35 # => ‘UI designer’ Q &A Friday, May 17, 13