As with all languages the ability to encapsulate and reuse code is always important and if nothing else keeps the code concise and readable, one of the main aims of Ruby. In this example we take the existing Decimal to Binary IP address convertor and add to it a methods. We can choose then to re-use this method in later projects should be wish.
As Ruby is interpreted rather than compiled we must define methods before they are used, This then will usually mean that in our code the methods are defines at the start of the script.
#!/usr/bin/ruby def do_convert(ip) ipa = ip.split('.') ipb1 = "%08b" % ipa[0] ipb2 = "%08b" % ipa[1] ipb3 = "%08b" % ipa[2] ipb4 = "%08b" % ipa[3] ipb = "#{ipb1}.#{ipb2}.#{ipb3}.#{ipb4}" printf "%-14s %-35sn","Dotted Decimal","#{ip}" printf "%-14s %-35sn","Binary", "#{ipb}" end
Using the keyword def we define the method do_convert in this case. We accept one input parameter ip to the method and this is used as a local variable to the method. This means that it is available in the scope that starts def and is out of scope after end.
Now that we have the method defines and tidied the code to ensure that we only access variables local to the method. We can run the rest of the code similar to before:
print "Enter an IP Address .. " STDOUT.flush ips = gets.chomp do_convert(ips)
Where we prompt for the input address and pass that through to the method to be processed. This code though has to come after the method as we cannot make reference to methods that have not , as yet, been defined.