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
Basic Ruby Syntax sum = 0 Newline is statement separator i = 1 while i <= 10 do sum += i*I i = i + 1 do ... end instead of { ... } end puts "Sum of squares is #{sum}\n" Optional parentheses in method invocation CS 142 Lecture Notes: Ruby Slide 1 Variable Names foo Local variable $foo Global variable @foo Instance variable in object @@foo Class variable MAX_USERS Constant (by convention) CS 142 Lecture Notes: Ruby Slide 2 Iterators and Blocks Method on Array object [1, 2, 3, 4].each do |x| print x + "\n" end Block: code passed to method CS 142 Lecture Notes: Ruby Slide 3 Yield def oddNumbers(count) number = 1 while count > 0 do yield(number) number += 2 count -= 1 end end Invoke method’s block oddNumbers(5) do |i| print(i, "\n") end CS 142 Lecture Notes: Ruby Slide 4 Factorial def fac(x) if x <= 0 then return 1 end return x*fac(x-1) end CS 142 Lecture Notes: Ruby Slide 5 Arguments: Defaults, Variable # def inc(value, amount=1) value+amount end def max(first, *rest) max = first rest.each do |x| if (x > max) then max = x end end return max end CS 142 Lecture Notes: Ruby Slide 6 Keyword Arguments def create_widget(size, properties) ... end create_widget(6, {:name => "Alice", :age => 31}) create_widget(6, :name => "Alice", :age => 31) CS 142 Lecture Notes: Ruby Slide 7 Simple Class class Point def initialize(x, y) @x = x @y = y end def x @x end def x=(value) @x = value end end p = Point.new(3,4) puts "p.x is #{p.x}\n" p.x = 44; CS 142 Lecture Notes: Ruby Slide 8 Module Example class MyClass include Enumerable ... def each ... end end New methods available in MyClass: min, max, sort, map, select, ... CS 142 Lecture Notes: Ruby Slide 9 CS 142 Lecture Notes: Ruby Slide 10