Tuesday, January 10, 2017

Going with Ruby

Today I decided to try some different languages just to see what would happen. I decided to try Ruby, just because it was on my laptop. Created by Yukihiro "Matz” Matsumoto around 1995, Ruby is one of those dynamic languages, primevally used on the Web. I have found out however that it’s also quite general so can be used as an alternative for Bash.
I took a simple edge case computation to try out. This is where a string of binary numbers is suppled and the program notes when the pattern changes. It’s a fairly simple problem, but nice as it hits all the main pain points, input for users, validation, loops, output of results, etc.
I’m happy to say it was a really simple language to understand. The “IRB” (Interactive RuBy) command within Terminal, lets you try out code on the fly. Getting the script to run on the Mac required a change to permissions to give it execute rights (“chmod 777”), but that’s was acceptable.
#!/usr/bin/env ruby
# Edge detection script
input = gets.chomp
if not (input =~ /[^0-1]/).nil? then
    puts "Error: Only 0-1 values allowed. e.g. 0100001111"
    exit
end
prevChar = "0"
result = ""
begin
   input.split("").each do |currentChar|
    # XOR each char against the previous
    edge = (prevChar.to_i(2) ^ currentChar.to_i(2)).to_s(2)
    result = result+"#{edge}"
    prevChar = currentChar
  end
puts "Input : #{input}"
puts "Output: #{result}"
rescue Exception => e
puts 'There was an unexpected error processing. ' + e.messageend 
end
All in all, it’s a nice language