1 / 23

Basic Ruby Syntax

Basic Ruby Syntax. No variable declarations. sum = 0 i = 1 while i &lt;= 10 do sum += i * i i = i + 1 end puts &quot;Sum of squares is #{sum}<br>&quot;. Newline is statement separator. do ... end instead of { ... }. Optional parentheses in method invocation. Substitution in string value.

saxon
Télécharger la présentation

Basic Ruby Syntax

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic Ruby Syntax No variable declarations sum = 0 i = 1 whilei <= 10 do sum += i*i i = i + 1 end puts "Sum of squares is #{sum}\n" Newline is statement separator do ... end instead of { ... } Optional parentheses in method invocation Substitution instring value CS 142 Lecture Notes: Ruby

  2. Variable Names and Scopes foo Local variable $foo Global variable @foo Instance variable in object @@foo Class variable MAX_USERS “Constant” (by convention) CS 142 Lecture Notes: Ruby

  3. Ruby String Syntax • Single quotes (only \' and \\) 'Bill\'s "personal" book' • Double quotes (many escape sequences) "Found #{count} errors\nAborting job\n" • %q (similar to single quotes) %q<Nesting works: <b>Hello</b>> • %Q (similar to double quotes) %Q|She said "#{greeting}"\n| • “Here documents” <<END First line Second line END CS 142 Lecture Notes: Ruby

  4. Arrays and Hashes x = Array.new x << 10 x[0] = 99 y = ["Alice", 23, 7.3] x[1] = y[1] + y[-1] person = Hash.new person["last_name"] = "Rodriguez" person[:first_name] = "Alice" order = {"item" => "Corn Flakes", "weight" => 18} order = {:item => "Corn Flakes", :weight => 18} order = {item: "Corn Flakes", weight: 18} CS 142 Lecture Notes: Ruby

  5. Ruby Statements if x < 10 then ... elsifx < 20 ... else ... end while x < 10 do ... end array = [14, 22, 34, 46, 92] for value in array do ... end CS 142 Lecture Notes: Ruby

  6. Factorial deffac(x) if x <= 1 then return 1 end return x*fac(x-1) end CS 142 Lecture Notes: Ruby

  7. Arguments: Defaults, Variable # definc(value, amount=1) value+amount end defmax(first, *rest) result= first for x in rest do if (x > result) then result= x end end returnresult end CS 142 Lecture Notes: Ruby

  8. Keyword Arguments defcreate_widget(size, properties) ... end create_widget(6, {:id => "table22", :class => "Cart"}) create_widget(6, :id => "table22", :class => "Cart") create_widget(6, id: "table22", class: "Cart") CS 142 Lecture Notes: Ruby

  9. Default, Hash, Keyword def f_default(size=10, color="black", bg="white") def f_hash(properties) def f_keyword(size:10, color:"black", bg:"white") f_default 20 #+ f_default 20, "green", "red" #+ f_default 20, bg="red" #? f_hash 20 #- f_hash({:size => 20}) #+ f_hash(:bg => "red", :color => "green", :size => 20)#+ f_hash(bg:"red", color:"green", size:20) #+ f_keyword(bg:"red", color:"green", size:20) #+ f_keyword 20, "red" #- CS 142 Lecture Notes: Ruby

  10. Calling Functions def max(first, *rest) … end max(5,6) max 5,6 max (5,6) # Avoid! CS 142 Lecture Notes: Ruby

  11. Symbols vs. Strings staff = ["Phil", "Firas", "JJ", "Andy"] faculty = ["Phil"] staff = [:Phil, :Firas, :JJ, :Andy] faculty = [:Phil] faculty "Phil" "Phil" with Strings "Firas" staff "JJ" "Andy" faculty :Phil with Symbols :Firas staff :JJ :Andy CS 142 Lecture Notes: Ruby

  12. Equivalent Code array = [14, 22, 34, 46, 92] for value in array do print(value, "\n") end array = [14, 22, 34, 46, 92]; array.eachdo |value| print(value, "\n") end Block: code passedto method CS 142 Lecture Notes: Ruby

  13. Blocks, Iterators, Yield odd_numbers(3) do |i| print(i, "\n") end defodd_numbers(count) number = 1 while count > 0 do yield(number) number += 2 count -= 1 end end Block: code passedto method Invoke method’s block CS 142 Lecture Notes: Ruby

  14. Blocks: Map, Select, Reduce names = ['Vien', 'Omosola', 'Sarah'] lookup = {'Vien' => 'viendinh', 'Omosola' => 'omosolao', 'Sarah' => 'ssterman'} logins = names.mapdo |n| lookup[n] end vnames = names.selectdo |n| n[0] == 'V' end namelist = names.reducedo |sum,val| sum = sum + " and " + val end CS 142 Lecture Notes: Ruby

  15. Iterators are Reusable defsum_odd(count) sum = 0 odd_numbers(count) do |i| sum += i end return sum end defodd_numbers(count) number = 1 while count > 0 do yield(number) number += 2 count -= 1 end end CS 142 Lecture Notes: Ruby

  16. Simple Class class Point definitialize(x, y) @x = x @y = y end defx @x end defx=(value) @x = value end end p = Point.new(3,4) puts "p.x is #{p.x}" p.x = 44 CS 142 Lecture Notes: Ruby

  17. Reduce Example (extending Array) namelist = names.ereducedo |sum,val| sum = sum + " and " + val end class Array def ereduce() sum = self[0] if (size < 2) then return sum end values =last(size - 1) values.eachdo |v| sum = yield(sum, v) end return sum end end CS 142 Lecture Notes: Ruby

  18. Module Examples module FileSaver def FileSaver::try_saving_file(input, dir, name) … end end require 'file_saver.rb' FileSaver::try_saving_file "Test", "./", "test.txt" module ConfigurationParams ROOT_DIR = "/home/pal" USER_NAME = "pal" end CS 142 Lecture Notes: Ruby

  19. ereduceMixin module EReduce def ereduce() sum = self[0] if (size < 2) then return sum end values =last(size - 1) values.eachdo |v| sum = yield(sum, v) end return sum end end class Array include EReduce end CS 142 Lecture Notes: Ruby

  20. Mixin Example New methods available in MyClass: min, max, sort, map, select, ... classMyClass include Enumerable ... defeach ... end def<=> ... end end CS 142 Lecture Notes: Ruby

  21. Simple Class class Point definitialize(x, y) @x = x @y = y end defx @x end defx=(value) @x = value end end p = Point.new(3,4) puts "p.x is #{p.x}" p.x = 44 CS 142 Lecture Notes: Ruby

  22. Metaprogramming • Programs that write programs! • eval, instance_eval, class_eval class Automobile include Extendable End a = Automobile.new a.add_variable :color a.add_variable :brand a.color = "green" a.brand = "Mazda" puts a.color, a.brand Mixin that gives the add_variablemethod These method invocations add accessor functions CS 142 Lecture Notes: Ruby

  23. CS 142 Lecture Notes: Ruby

More Related