Ruby – First Day – Testing




Ruby has a lot of interesting aspects. It is dynamically and inference typed meaning that you don’t have to declare what type a variable is nor do you need to keep it the same type. i = 4 can be followed by i = “Hello”. It can also have different types in the same array. It also is purely object oriented meaning there are no primitives. All numbers, strings, everything is objects. All numbers can call methods like 5.even to see if the number is even.

irb starts an interactive interpreter. It’s great for running test cases and quick code. This avoids needing to write out stupid class headers and compile Java classes. This is fast and great.

Unique Structures to Ruby

#case control structure
r = rand(100)
when r.even?
 print r, " is even\n"
when r < 10
 print r, " is small\n"
 print r, " is big and odd\n"

Conditionals don’t need () or {} and can come at the ends of statements

puts "x is not even" unless x.even?

No semicolons needed

Here’s a one liner for finding the factors of a number.

def factors(n)
 return (1..n).select {|x| n % x == 0}


(1..n) creates an array with the values going 1 to n. The select block iterates over every item in the list and checks to see if it has a mod result of 0. rand gives a random number between 0 and n-1 so 1-99 in this case.


require 'test/unit'
load './mod6PA.rb'
class TestFactor < Test::Unit::TestCase
 def test_factor
 output = factors(-1)
 assert_equal [], output

In irb just run the test file ruby testFile.rb