Example Ruby code

I decided to do some of those Facebook puzzles in Ruby. I won’t post everything I do, because I would consider that cheating (after all, you can win prizes!).

However, considering this is a very simple script, and I’m doing it more for learning Ruby than to enter into Facebook’s puzzles, I will post this one.

This is the first puzzle, called Hoppity Hop:

private
@file_exists = false
def get_integer(filename)
    if File::exists?(filename)
        file = File.open(filename)
        line = file.gets.strip!
        file.close
        @file_exists = true
        return line.to_i
    else
        @file_exists = false
        return 0 #zero files present
    end
end

def get_string(num)
    if(num%3 == 0 && num%5 == 0)
        print "Hop\n"
    elsif num%3 == 0
        print "Hoppity\n"
    elsif num%5 == 0
        print "Hophop\n"
    else
        return #nothing
    end
end

def hip_hop(arg)
    num = get_integer(arg)
    if(num > 0 && @file_exists)
        for i in 1..num.to_i
            get_string(i)
        end
    else
        puts "File not found"
    end
end

public

arg = ARGV[0].to_s # this is the name of the file
if(/\D/ =~ arg)
    puts "Please enter a positive integer as the filename."
else
    unless arg == nil
        hip_hop(arg)
    end
end

Related Articles