Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 142 Lecture Notes: RubySlide 1 Basic Ruby Syntax sum = 0 i = 1 while i <= 10 do sum += i*I i = i + 1 end puts "Sum of squares is #{sum}\n" Newline is.

Similar presentations


Presentation on theme: "CS 142 Lecture Notes: RubySlide 1 Basic Ruby Syntax sum = 0 i = 1 while i <= 10 do sum += i*I i = i + 1 end puts "Sum of squares is #{sum}\n" Newline is."— Presentation transcript:

1 CS 142 Lecture Notes: RubySlide 1 Basic Ruby Syntax sum = 0 i = 1 while i <= 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

2 CS 142 Lecture Notes: RubySlide 2 Variable Names foo Local variable $foo Global variable @foo Instance variable in object @@foo Class variable MAX_USERS Constant (by convention)

3 CS 142 Lecture Notes: RubySlide 3 Iterators and Blocks [1, 2, 3, 4].each do |x| print x + "\n" end Method on Array object Block: code passed to method

4 CS 142 Lecture Notes: RubySlide 4 Yield def oddNumbers(count) number = 1 while count > 0 do yield(number) number += 2 count -= 1 end oddNumbers(5) do |i| print(i, "\n") end Invoke method’s block

5 CS 142 Lecture Notes: RubySlide 5 Factorial def fac(x) if x <= 0 then return 1 end return x*fac(x-1) end

6 CS 142 Lecture Notes: RubySlide 6 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 return max end

7 CS 142 Lecture Notes: RubySlide 7 Keyword Arguments def create_widget(size, properties)... end create_widget(6, {:name => "Alice", :age => 31}) create_widget(6, :name => "Alice", :age => 31)

8 CS 142 Lecture Notes: RubySlide 8 Simple Class class Point def initialize(x, y) @x = x @y = y end def x @x end def x=(value) @x = value end p = Point.new(3,4) puts "p.x is #{p.x}\n" p.x = 44;

9 CS 142 Lecture Notes: RubySlide 9 Module Example class MyClass include Enumerable... def each... end New methods available in MyClass: min, max, sort, map, select,...

10 CS 142 Lecture Notes: RubySlide 10


Download ppt "CS 142 Lecture Notes: RubySlide 1 Basic Ruby Syntax sum = 0 i = 1 while i <= 10 do sum += i*I i = i + 1 end puts "Sum of squares is #{sum}\n" Newline is."

Similar presentations


Ads by Google