dir = Dir.new("dir") entries = [] dir.each { |file| entries << file } assertEquals([".", ".."], entries) entries = [] Dir.foreach("dir") do |file| if file[0..0] != "." entries << file end end assertEquals([], entries)
#!/usr/bin/env ruby l = [] l << "bla" x = "" for i in 0..5 do x += i.to_s end assertEquals("012345", x) x = "" i = 0 begin x += i.to_s i += 1 end while i <= 5 assertEquals("012345", x) x = "" i = 0 while i <= 5 x += i.to_s i += 1 end assertEquals("012345", x) # Can we handle classes as objects? Yes x = Address a = x.new("Elfgenweg 14", "Duesseldorf") print a, "\n" assertEquals("Germany", a.country) #---------------------------------------------------------------------- # blocks and iterators s = "" (0..5).each { |i| s += i.to_s } assertEquals("012345", s) s = "" (0..5).to_a.reverse_each { |i| s += i.to_s } assertEquals("543210", s) assertEquals([2, 4], [1, 2].collect {|i| 2 * i}) #---------------------------------------------------------------------- # Scoping def testScope() # As in python, "if" statements do not define a new scope if 1 innerX = 5 end assertEquals(5, innerX) # The same is true for loops for i in [1, 2] do innerY = 6 end assertEquals(6, innerY) end testScope() #---------------------------------------------------------------------- # Function "pointers" # # The function "proc" converts a block into a function (Proc) object. # This includes the context (here the variable x). class Button def initialize(label, action) @label = label @action = action end def press @action.call() end end x = "this is " b = Button.new("bla", proc { x + "blub" }) assertEquals("this is blub", b.press) #---------------------------------------------------------------------- #