    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: A Glint of Ruby</title>
        <link>https://members.accu.org/index.php/journals/2416</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 29, #4 - September 2017 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c377/">294</a>
                    (10)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c377-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c377+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;A Glint of Ruby</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 06 September 2017 16:23:46 +01:00 or Wed, 06 September 2017 16:23:46 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Pete Cordell shares his experiences with learning a new scripting language.</p>
<p><strong>Body:</strong>&nbsp;<p>I mainly program in C++. I also use C# for Windows GUI programming, PHP for web work and a scripting language for odd tasks such as analysing text files or running tests.</p>

<p>I have been using Perl in the scripting language role. However, even I had to admit that that was getting long in the tooth and it would be good for my skill set to move onto something more modern. The logical choice was Python. Iâ€™ll admit that I never really got on with Python. The sorts of things I wanted to do often seemed harder to do in Python than in Perl. But Python seemed to be the way things should be done, so I decided to persevere. Then, by chance, I got involved in a project with someone who was using Ruby <a href="#[1]">[1]</a>. After an initial â€˜whateverâ€™, it has been love at first sight ever since!</p>

<p>I tell you this to put the rest of the article into context. Iâ€™m not an experienced Ruby programmer, and like an infatuated teenager, I may well be blind to any warts the language might have.</p>

<p>There are many Ruby tutorials online, so I donâ€™t intend to teach you Ruby here. Instead, my aim is to help you recognise a Ruby program when you see one, try to pique your interest in learning more about Ruby, and cover a few things that might be intriguing to a C++ (and possibly Python) programmer not familiar with Ruby.</p>

<p>You may already have Ruby on your system if you are using Linux. If not, you should find a suitable download option at <a href="#[2]">[2]</a>. In addition to providing the ability to run Ruby programs on your system, you should also find an interactive Ruby shell called <code>irb</code>. This is very handy for experimenting with Ruby, and you may wish to use it to play around with some of the examples below (most of which you should find at <a href="#[3]">[3]</a>).</p>

<h2>A contrived example</h2>

<p>The obligatory â€œHello, World!â€ program looks as follows in Ruby:</p>

<pre class="programlisting">
  puts &quot;Hello, World!&quot;</pre>
  
<p>Itâ€™s always a good sign when a scripting language allows â€œHello, World!â€ to be a one-liner, but it doesnâ€™t tell us much about the language. So, in the spirit of feature creep, letâ€™s look at Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
# A class to say Hello
class Greeter
  def initialize( who )
    @who = who
  end
  def greet
    if @who =~ /^\s*PETE\s*$/i
      puts &quot;Hello author&quot;
    else
      named_greeting
    end
  end
  private def named_greeting
    puts &quot;Hello #{@who}&quot;
  end
end
greeter = Greeter.new &quot;reader&quot;
greeter.greet
Greeter.new( &quot; Pete &quot; ).greet
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>Working through the example, comments start with the <code>#</code> character and continue to the end of the line.</p>

<p>Class names (i.e. <code>Greeter</code>) must begin with a capital letter, and, by convention, use PascalCase.</p>

<p>Chunks of code (a â€˜blockâ€™ has a special meaning in Ruby so Iâ€™m avoiding its usage here) typically start with a keyword such as <code>class</code>, <code>def</code>, <code>if</code>, <code>while</code> and continue until a matching <code>end</code> keyword.</p>

<p>Indenting is not particularly important in Ruby. The Ruby style guide specifies two spaces per tab. Iâ€™m yet to get comfortable with that, but Iâ€™ve adopted it here as itâ€™s more idiomatic, and better for presentation in a print publication.</p>

<p>The <code>def</code> keyword defines a method. Method names typically are all lower-case and sub-words are underscore separated. The last character can also be one of <code>?</code>, <code>!</code> or <code>=</code>. The <code>initialize</code> method is analogous to a constructor in C++, and is called when a new instance of an object is created.</p>

<p>The scope of variables in Ruby is indicated by an optional prefixed character. Without a prefix, a variable is local to the chunk it is defined in. Variables prefixed by a single <code>@</code> character have object instance scope. Variables prefixed by <code>@@</code> have class scope, similar to C++ <code>static</code> class variables. Variables prefixed by <code>$</code> are global. So, the line <code>@who = who</code> translated to Python would look like <code>self.who = who</code>. Variables names must begin with a lower-case letter or underscore, and, by convention, are all lower-case with sub-words separated by underscores (e.g. <code>my_variable</code>). (Constants on the other hand must start with an upper-case letter, and are usually all upper-case along with underscore separators, e.g. <code>MY_CONSTANT</code>.)</p>

<p>Moving onto the <code>greet</code> method, we get our first glimpse of how minimalist and token free Ruby can be. There are no brackets around the <code>if</code> clause and there is no delimiter such as <code>then</code> or <code>:</code> to explicitly mark the end of the condition. One of the goals of the Ruby designer (Yukihiro Matsumoto, or Matz to his friends) was to make programming faster and easier. One aspect of this is to make the interpreter work harder in order to make life for the programmer easier. Typically a Ruby expression ends at the end of a line, unless there is some kind of binary operator, or a <code>,</code> to suggest that there is more on the next line. Sometimes additional brackets are needed for disambiguation (and semi-colons can be used to terminate expressions), but the preferred Ruby style is to avoid them if possible. This can take a bit of getting used to, but after a while the result looks more narrative like than typical C++ programs.</p>

<p>The condition of the <code>if</code> expression shows that regular expressions have first-class support in Ruby. Those with a Perl background will find this syntax familiar.</p>

<p>The <code>puts</code> method call should be familiar to C++ programmers, although you may be excused for having forgotten about it. <code>puts</code> prints its arguments to standard output, followed by a newline sequence. If you donâ€™t want the newline characters, use <code>print</code> instead.</p>

<p>Moving to the <code>else</code> clause we have a call to the <code>named_greeting</code> method. Unlike in Python, there is no need to prefix a call to another method in the same object with <code>self.</code>.</p>

<p>The <code>named_greeting</code> method definition itself is preceded by the <code>private</code> method, showing Ruby gives you the ability to control access to object methods. Note that <code>private</code> isnâ€™t a keyword like in C++, but a method call. Thereâ€™s some Ruby subtlety here which is too detailed to go into in this article. Suffice to say that the use of <code>private</code> on the same line as a <code>def</code> will make only that method private (similar to Java and C#â€™s usage), whereas <code>private</code> on its own line (a call to <code>private</code> with no arguments) will make all following methods private (similar to C++â€™s usage).</p>

<p>The <code>puts</code> line in <code>named_greeting</code> shows Rubyâ€™s syntax for string interpolation. Many scripting languages support string interpolation, but Ruby takes this to the max. The code between the opening <code>#{</code> and closing <code>}</code> can be any expression and is not limited to just variables. It can include operators, method calls, and even <code>if</code> statements. If the result of the expression is not a string, then the interpreter will automatically convert it to one.</p>

<p>The class definition described creates a runtime object called <code>Greeter</code>. That object includes a method called <code>new</code>. When the <code>new</code> method is called on the <code>Greeter</code> object, it creates a new object that conforms to the class definition. It then calls the newly created objectâ€™s <code>initialize</code> method with the arguments given in the <code>new</code> method call. Note again that there are no brackets around the arguments to the <code>new</code> method call.</p>

<p>In the example, we assign a reference to the new object to the <code>greeter</code> variable. Once we have a reference to an object instance, we can invoke methods on it as shown by the expression <code>greeter.greet</code>.</p>

<p>As you might expect, Ruby is garbage collected so thereâ€™s no need to clean up any objects that have been created.</p>

<p>Hopefully it wonâ€™t be a surprise to you that the output of the program is:</p>

<p>    Hello reader</p>
<p>    Hello author</p>

<h2>Digging for gems</h2>

<p>Now you hopefully have a feel for what a Ruby program looks like, letâ€™s have a closer look at a few things that might be intriguing to a programmer who only knows C++, and things that are more unique to Ruby.</p>

<h2>Objects everywhere</h2>

<p>Everything in Ruby is an object. There are no primitive, machine word level types such as <code>char</code>, <code>int</code> and <code>float</code> like you find in C++. Consequently, you can call methods directly on explicit values such as floating-point numbers. For example, <code>1.5.round</code> evaluates to <code>2</code>.</p>

<p>All classes are open to extension in Ruby and are similar to C# partial classes. For example, you can augment the <code>Float</code> class with your own methods (although this isnâ€™t a recommendation to do it). The following program outputs <code>4.5</code>:</p>

<pre class="programlisting">
  class Float
    def triple
      3 * self
    end
  end
  puts 1.5.triple</pre>
  
<p>It may look like the usage of <code>puts</code> above is a free-standing function. But it is actually a member of the <code>Object</code> class from which all objects derive. The other â€˜fudgeâ€™ is that the outer-most level of execution takes place within the scope of an automatically defined, but largely hidden, object called <code>main</code>.</p>

<h2>Types and whatâ€™s true</h2>

<p>In addition to numbers, strings and the regular expressions already mentioned, Ruby also supports arrays and hashes using the handy syntax youâ€™d expect from a scripting language. Additionally, Ruby has a range type which captures a start value and an end value within a single object. Iâ€™ll touch on ranges in a bit, but hereâ€™s some examples of the syntax for these types:</p>

<pre class="programlisting">
  my_array = [ 1, 2, 3, &quot;Four&quot;, 5 ]
  my_hash = { &quot;author&quot; =&gt; &quot;Pete&quot;,
              &quot;reader&quot; =&gt; &quot;you&quot; }
  my_range = 0..10</pre>
  
<p>Ruby will automatically convert between numbers of different types (for example, integer to floating point number) as the operations require. But unlike some languages, outside of string interpolation, it wonâ€™t automatically convert to and from numerical types and strings.</p>

<p>As with Python, but not with Perl, Ruby has a <code>Bignum</code> type that can store integers of any size. If integer operations get too big to fit within a native machine sized integer, they will be transparently converted to a <code>Bignum</code>. This is shown in the following code, where <code>**</code> is the â€˜to the power ofâ€™ operator, and the output is shown in the comments:</p>

<pre class="programlisting">
  puts 2**4          # 16
  puts (2**4).class  # Fixnum
  puts 2**70         # 1180591620717411303424
  puts (2**70).class # Bignum
  puts (2**70/
        2**60).class # Fixnum</pre>

<p>Then there is <code>true</code>, <code>false</code> and <code>nil</code>. <code>nil</code> is equivalent to C#â€™s <code>null</code> and Pythonâ€™s <code>None</code>. Only <code>false</code> and <code>nil</code> are treated as false in conditional expressions. Everything else is treated as true, including <code>0</code>, empty strings and empty arrays. Those familiar with Python and Perl might find the latter surprising, but it does seem to fit in with the language quite well. If nothing else, itâ€™s easy to remember!</p>

<h2>The block</h2>

<p>One of the more unique features of Ruby is the concept of a â€˜blockâ€™. Similar to lambdas, any method can be given a block which it can call with a set of parameters, and receive a result back. The â€˜blockâ€™ follows a method call, and is either contained between opening and closing braces, or the <code>do</code> and <code>end</code> keywords. The former syntax is typically used for one-line (or even in-line) blocks, and the latter for multi-line blocks. The arguments to the block are delimited by a pair of <code>|</code> pipe characters, and the value of the last expression executed in the block is returned to the calling method. For example, using the variables set up previously:</p>

<pre class="programlisting">
  my_array.each { |x| print &quot;_#{x}&quot; }
  puts  # Put new line at end of above
  my_hash.each do |role, name|
    if role == &quot;reader&quot;
      puts &quot;#{name}, Thanks for reading&quot;
    end
  end</pre>
  
<p>Outputs:</p>

<pre class="programlisting">
  _1_2_3_Four_5
  you, Thanks for reading</pre>
  
<p>Blocks are not limited to iterating through arrays and hashes.</p>

<p>If the <code>File.open</code> method is given a block, it will close the opened file on return from the block. As such, this usage scenario is similar to C#â€™s <code>using</code> and Pythonâ€™s <code>with</code> constructs.</p>

<p>In combination with suitable methods, blocks are often used as an alternative to conventional counted <code>for</code> loops. In place of C++ like:</p>

<pre class="programlisting">
  for (int i=0; i&lt;10; ++i)
    std::cout &lt;&lt; &quot;_&quot; &lt;&lt; i;</pre>

<p>you can do any of these (wherein the last one is an example of the range type I mentioned earlier):</p>

<pre class="programlisting">
  10.times { |x| print &quot;_#{x}&quot; }
  0.upto(9) { |x| print &quot;_#{x}&quot; }
  (0..9).each { |x| print &quot;_#{x}&quot; }</pre>
  
<p>Blocks, and the fact that most methods return something â€˜usefulâ€™, opens up the way to a more functional coding style. Among many functional-like methods, Ruby supports <code>map</code>, <code>select</code> and <code>reduce</code> on arrays. Using these, if you wanted to know the sum of the odd squared numbers, for the numbers 0 to 100, you could do:</p>

<pre class="programlisting">
  puts (0..100).map { |x| x * x }
    .select { |x| x.odd? }
    .reduce { |acc,x| acc + x }</pre>
	
<p>Why Ruby uses <code>select</code> rather than the more traditional <code>filter</code>, Iâ€™m not sure. If it bothers you, though, you can do <code>class Array; alias filter select; end</code> and use <code>filter</code> in your code instead.</p>

<p>One thing that perhaps should be said here is that I havenâ€™t been able to see how to make an expression like the above â€˜lazyâ€™ in the same way that Haskell does. Each method call creates a new array before the next method acts on it, rather than just acting on iterators. This wonâ€™t cause problems in many cases, but does prevent Haskell-like solutions of the form â€˜for all positive integersâ€¦â€™.</p>

<h2>Thereâ€™s moreâ€¦</h2>

<p>Thereâ€™s much more to Ruby than Iâ€™ve been able to cover here. Ruby has parallel assignment, slices, exceptions, threads and coroutines.</p>

<p>It also has an extensive library of third-party code in the form of RubyGems <a href="#[4]">[4]</a>, and a dependency management system called Bundler <a href="#[5]">[5]</a> that ensures that the correct versions of the Gems are installed for your program.</p>

<h2>Finding out more</h2>

<p>If you want to explore further, there are numerous Ruby tutorials on-line (e.g. <a href="#[6]">[6]</a>). I have found <em>The Ruby Programming Language</em> book <a href="#[7]">[7]</a> to be very good. This is a depth-first look at the language that assumes you already know a bit about programming. It feels as close to a language definition as you can get without having to be a language lawyer. The Ruby documentation <a href="#[8]">[8]</a> is good, but I find it hard to navigate. Hence, I tend to use Google as itâ€™s front-end! Googling will also bring you to Stack Overflow. Perhaps because Ruby is slightly less common than other languages, the answers for Ruby seem to be of a higher quality than you might find for other languages. The <code>irb</code> interactive Ruby shell is also a fun way to poke around to test your understanding.</p>

<h2>Conclusion</h2>

<p>I hope Iâ€™ve given you enough to be able to recognise a Ruby program. Possibly youâ€™re now interested in finding out a little more information. I can understand that some people might find the various naming constraints difficult to get over, but in my case I had already adopted similar rules, and so wasnâ€™t bothered. My biggest gripe is that if your code changes a constant, the Ruby interpreter will only generate a warning rather than an error. I console myself that, for the sorts of things I use Ruby for, I donâ€™t need a lot of constants. Those wanting to make more extensive use of Ruby might consider this more of an issue.</p>

<p>Overall, Iâ€™ve found code solving similar problems is simpler and clearer in Ruby than in other languages. As such, it has exceeded my expectations and I hope it will for you too.</p>

<h2>References</h2>
<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="https://www.ruby-lang.org/en/">https://www.ruby-lang.org/en/</a></p>

<p class="bibliomixed"><a id="[2]"></a>[2]	<a href="https://www.ruby-lang.org/en/downloads/">https://www.ruby-lang.org/en/downloads/</a></p>

<p class="bibliomixed"><a id="[3]"></a>[3]	<a href="https://github.com/codalogic/accu-ruby">https://github.com/codalogic/accu-ruby</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	<a href="https://www.ruby-lang.org/en/libraries/">https://www.ruby-lang.org/en/libraries/</a></p>

<p class="bibliomixed"><a id="[5]"></a>[5]	<a href="https://bundler.io/">https://bundler.io/</a></p>

<p class="bibliomixed"><a id="[6]"></a>[6]	<a href="https://www.ruby-lang.org/en/documentation/">https://www.ruby-lang.org/en/documentation/</a></p>

<p class="bibliomixed"><a id="[7]"></a>[7]	Flanagan, D &amp; Yukihiro Matsumoto, Y (2008), <em>The Ruby Programming Language</em>, Oâ€™Reilly.</p>

<p class="bibliomixed"><a id="[8]"></a>[8]	<a href="https://ruby-doc.org/core-2.4.1/">https://ruby-doc.org/core-2.4.1/</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
