<p>Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.</p>

<p>Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.</p>

<p>See also:</p>

<ul>
<li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden features of C#</a></li>
<li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li>
<li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden features of JavaScript</a></li>
<li><a href="https://stackoverflow.com/questions/709679/hidden-features-of-ruby-on-rails">Hidden features of Ruby on Rails</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li>
</ul>

<p>(Please, just <em>one</em> hidden feature per answer.)</p>

<p>Thank you</p>

[{'answer_id': 64080, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 5, 'selected': False, 'text': '<p>I find using the <strong>define_method</strong> command to dynamically generate methods to be quite interesting and not as well known.  For example:</p>\n\n<pre><code>((0..9).each do |n|\n    define_method "press_#{n}" do\n      @number = @number.to_i * 10 + n\n    end\n  end\n</code></pre>\n\n<p>The above code uses the \'define_method\' command to dynamically create the methods "press1" through "press9."  Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.</p>\n'}, {'answer_id': 64099, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 3, 'selected': False, 'text': '<p>The <strong>send()</strong> method is a general-purpose method that can be used on any Class or Object in Ruby.  If not overridden, send() accepts a string and calls the name of the method whose string it is passed.  For example, if the user clicks the “Clr” button, the ‘press_clear’ string will be sent to the send() method and the ‘press_clear’ method will be called.  The send() method allows for a fun and dynamic way to call functions in Ruby.</p>\n\n<pre><code> %w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|\n    button btn, :width =&gt; 46, :height =&gt; 46 do\n      method = case btn\n        when /[0-9]/: \'press_\'+btn\n        when \'Clr\': \'press_clear\'\n        when \'=\': \'press_equals\'\n        when \'+\': \'press_add\'\n        when \'-\': \'press_sub\'\n        when \'*\': \'press_times\'\n        when \'/\': \'press_div\'\n      end\n\n      number.send(method)\n      number_field.replace strong(number)\n    end\n  end\n</code></pre>\n\n<p>I talk more about this feature in <a href="http://www.codingwithoutcomments.com/2008/09/01/blogging-shoes-the-simple-calc-application/" rel="nofollow noreferrer">Blogging Shoes:  The Simple-Calc Application</a></p>\n'}, {'answer_id': 64124, 'author': 'manveru', 'author_id': 8367, 'author_profile': 'https://Stackoverflow.com/users/8367', 'pm_score': 5, 'selected': False, 'text': '<p>Download Ruby 1.9 source, and issue <code>make golf</code>, then you can do things like this:</p>\n\n<pre><code>make golf\n\n./goruby -e \'h\'\n# =&gt; Hello, world!\n\n./goruby -e \'p St\'\n# =&gt; StandardError\n\n./goruby -e \'p 1.tf\'\n# =&gt; 1.0\n\n./goruby19 -e \'p Fil.exp(".")\'\n"/home/manveru/pkgbuilds/ruby-svn/src/trunk"\n</code></pre>\n\n<p>Read the <code>golf_prelude.c</code> for more neat things hiding away.</p>\n'}, {'answer_id': 64427, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 4, 'selected': False, 'text': '<p>use anything that responds to <code>===(obj)</code> for case comparisons:</p>\n\n<pre><code>case foo\nwhen /baz/\n  do_something_with_the_string_matching_baz\nwhen 12..15\n  do_something_with_the_integer_between_12_and_15\nwhen lambda { |x| x % 5 == 0 }\n  # only works in Ruby 1.9 or if you alias Proc#call as Proc#===\n  do_something_with_the_integer_that_is_a_multiple_of_5\nwhen Bar\n  do_something_with_the_instance_of_Bar\nwhen some_object\n  do_something_with_the_thing_that_matches_some_object\nend\n</code></pre>\n\n<p><code>Module</code> (and thus <code>Class</code>), <code>Regexp</code>, <code>Date</code>, and many other classes define an instance method :===(other), and can all be used.</p>\n\n<p>Thanks to <a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby#65015">Farrel</a> for the reminder of <code>Proc#call</code> being aliased as <code>Proc#===</code> in Ruby 1.9.</p>\n'}, {'answer_id': 64458, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 6, 'selected': False, 'text': '<p>Peter Cooper has a <a href="http://www.rubyinside.com/21-ruby-tricks-902.html" rel="nofollow noreferrer">good list</a> of Ruby tricks.  Perhaps my favorite of his is allowing both single items and collections to be enumerated.  (That is, treat a non-collection object as a collection containing just that object.)  It looks like this:</p>\n\n<pre><code>[*items].each do |item|\n  # ...\nend\n</code></pre>\n'}, {'answer_id': 64502, 'author': 'Scott Holden', 'author_id': 8588, 'author_profile': 'https://Stackoverflow.com/users/8588', 'pm_score': 3, 'selected': False, 'text': "<p>How about opening a file based on ARGV[0]?</p>\n\n<p><code>readfile.rb:</code></p>\n\n<pre><code>$&lt;.each_line{|l| puts l}\n\nruby readfile.rb testfile.txt\n</code></pre>\n\n<p>It's a great shortcut for writing one-off scripts.  There's a whole mess of pre-defined variables that most people don't know about.  Use them wisely (read: don't litter a code base you plan to maintain with them, it can get messy).</p>\n"}, {'answer_id': 64956, 'author': 'TALlama', 'author_id': 5657, 'author_profile': 'https://Stackoverflow.com/users/5657', 'pm_score': 4, 'selected': False, 'text': '<p>A lot of the magic you see in Rubyland has to do with metaprogramming, which is simply writing code that writes code for you. Ruby\'s <code>attr_accessor</code>, <code>attr_reader</code>, and <code>attr_writer</code> are all simple metaprogramming, in that they create two methods in one line, following a standard pattern. Rails does a whole lot of metaprogramming with their relationship-management methods like <code>has_one</code> and <code>belongs_to</code>.</p>\n\n<p>But it\'s pretty simple to create your own metaprogramming tricks using <code>class_eval</code> to execute dynamically-written code.</p>\n\n<p>The following example allows a wrapper object to forwards certain methods along to an internal object:</p>\n\n<pre><code>class Wrapper\n  attr_accessor :internal\n\n  def self.forwards(*methods)\n    methods.each do |method|\n      define_method method do |*arguments, &amp;block|\n        internal.send method, *arguments, &amp;block\n      end\n    end\n  end\n\n  forwards :to_i, :length, :split\nend\n\nw = Wrapper.new\nw.internal = "12 13 14"\nw.to_i        # =&gt; 12\nw.length      # =&gt; 8\nw.split(\'1\')  # =&gt; ["", "2 ", "3 ", "4"]\n</code></pre>\n\n<p>The method <code>Wrapper.forwards</code> takes symbols for the names of methods and stores them in the <code>methods</code> array. Then, for each of those given, we use <code>define_method</code> to create a new method whose job it is to send the message along, including all arguments and blocks.</p>\n\n<p>A great resource for metaprogramming issues is <a href="http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html" rel="noreferrer">Why the Lucky Stiff\'s "Seeing Metaprogramming Clearly"</a>.</p>\n'}, {'answer_id': 65015, 'author': 'Farrel', 'author_id': 7889, 'author_profile': 'https://Stackoverflow.com/users/7889', 'pm_score': 6, 'selected': False, 'text': '<p>From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:</p>\n\n<pre><code>def multiple_of(factor)\n  Proc.new{|product| product.modulo(factor).zero?}\nend\n\ncase number\n  when multiple_of(3)\n    puts "Multiple of 3"\n  when multiple_of(7)\n    puts "Multiple of 7"\nend\n</code></pre>\n'}, {'answer_id': 68037, 'author': 'olegueret', 'author_id': 10421, 'author_profile': 'https://Stackoverflow.com/users/10421', 'pm_score': 3, 'selected': False, 'text': '<p>Fool some class or module telling it has required something that it really hasn\'t required:</p>\n\n<pre><code>$" &lt;&lt; "something"\n</code></pre>\n\n<p>This is useful for example when requiring A that in turns requires B but we don\'t need B in our code (and A won\'t use it either through our code):</p>\n\n<p>For example, Backgroundrb\'s <code>bdrb_test_helper requires</code> <code>\'test/spec\'</code>, but you don\'t use it at all, so in your code:</p>\n\n<pre><code>$" &lt;&lt; "test/spec"\nrequire File.join(File.dirname(__FILE__) + "/../bdrb_test_helper")\n</code></pre>\n'}, {'answer_id': 68205, 'author': 'hoyhoy', 'author_id': 3499, 'author_profile': 'https://Stackoverflow.com/users/3499', 'pm_score': 5, 'selected': False, 'text': '<p>The Symbol#to_proc function that Rails provides is really cool.  </p>\n\n<p>Instead of</p>\n\n<pre><code>Employee.collect { |emp| emp.name }\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>Employee.collect(&amp;:name)\n</code></pre>\n'}, {'answer_id': 69091, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Warning: this item was voted #1 <strong><em>Most Horrendous Hack of 2008</em></strong>, so use with care.  Actually, avoid it like the plague, but it is most certainly Hidden Ruby.</p>\n\n<h2>Superators Add New Operators to Ruby</h2>\n\n<p>Ever want a super-secret handshake operator for some unique operation in your code?  Like playing code golf?  Try operators like\n    -~+~-\nor\n    &lt;---\nThat last one is used in the examples for reversing the order of an item.</p>\n\n<p>I have nothing to do with the <a href="http://jicksta.com/posts/superators-add-new-operators-to-ruby" rel="nofollow noreferrer">Superators Project</a> beyond admiring it.</p>\n'}, {'answer_id': 70116, 'author': 'Farrel', 'author_id': 7889, 'author_profile': 'https://Stackoverflow.com/users/7889', 'pm_score': 5, 'selected': False, 'text': '<p>Another fun addition in 1.9 Proc functionality is Proc#curry which allows you to turn a Proc accepting n arguments into one accepting n-1. Here it is combined with the Proc#=== tip I mentioned above:</p>\n\n<pre><code>it_is_day_of_week = lambda{ |day_of_week, date| date.wday == day_of_week }\nit_is_saturday = it_is_day_of_week.curry[6]\nit_is_sunday = it_is_day_of_week.curry[0]\n\ncase Time.now\nwhen it_is_saturday\n  puts "Saturday!"\nwhen it_is_sunday\n  puts "Sunday!"\nelse\n  puts "Not the weekend"\nend\n</code></pre>\n'}, {'answer_id': 70203, 'author': 'astronautism', 'author_id': 11424, 'author_profile': 'https://Stackoverflow.com/users/11424', 'pm_score': 6, 'selected': False, 'text': '<p>Don\'t know how hidden this is, but I\'ve found it useful when needing to make a Hash out of a one-dimensional array:</p>\n\n<pre><code>fruit = ["apple","red","banana","yellow"]\n=&gt; ["apple", "red", "banana", "yellow"]\n\nHash[*fruit]    \n=&gt; {"apple"=&gt;"red", "banana"=&gt;"yellow"}\n</code></pre>\n'}, {'answer_id': 70286, 'author': 'tomafro', 'author_id': 7126, 'author_profile': 'https://Stackoverflow.com/users/7126', 'pm_score': 6, 'selected': False, 'text': '<p>One trick I like is to use the splat (<code>*</code>) expander on objects other than Arrays. Here\'s an example on a regular expression match:</p>\n\n<pre><code>match, text, number = *"Something 981".match(/([A-z]*) ([0-9]*)/)\n</code></pre>\n\n<p>Other examples include:</p>\n\n<pre><code>a, b, c = *(\'A\'..\'Z\')\n\nJob = Struct.new(:name, :occupation)\ntom = Job.new("Tom", "Developer")\nname, occupation = *tom\n</code></pre>\n'}, {'answer_id': 85310, 'author': 'tomafro', 'author_id': 7126, 'author_profile': 'https://Stackoverflow.com/users/7126', 'pm_score': 6, 'selected': False, 'text': '<p>Another tiny feature - convert a <code>Fixnum</code> into any base up to 36:</p>\n\n<pre><code>&gt;&gt; 1234567890.to_s(2)\n=&gt; "1001001100101100000001011010010"\n\n&gt;&gt; 1234567890.to_s(8)\n=&gt; "11145401322"\n\n&gt;&gt; 1234567890.to_s(16)\n=&gt; "499602d2"\n\n&gt;&gt; 1234567890.to_s(24)\n=&gt; "6b1230i"\n\n&gt;&gt; 1234567890.to_s(36)\n=&gt; "kf12oi"\n</code></pre>\n\n<p>And as Huw Walters has commented, converting the other way is just as simple:</p>\n\n<pre><code>&gt;&gt; "kf12oi".to_i(36)\n=&gt; 1234567890\n</code></pre>\n'}, {'answer_id': 86238, 'author': 'tomafro', 'author_id': 7126, 'author_profile': 'https://Stackoverflow.com/users/7126', 'pm_score': 5, 'selected': False, 'text': '<p>One final one - in ruby you can use any character you want to delimit strings.  Take the following code:</p>\n\n<pre><code>message = "My message"\ncontrived_example = "&lt;div id=\\"contrived\\"&gt;#{message}&lt;/div&gt;"\n</code></pre>\n\n<p>If you don\'t want to escape the double-quotes within the string, you can simply use a different delimiter:</p>\n\n<pre><code>contrived_example = %{&lt;div id="contrived-example"&gt;#{message}&lt;/div&gt;}\ncontrived_example = %[&lt;div id="contrived-example"&gt;#{message}&lt;/div&gt;]\n</code></pre>\n\n<p>As well as avoiding having to escape delimiters, you can use these delimiters for nicer multiline strings:</p>\n\n<pre><code>sql = %{\n    SELECT strings \n    FROM complicated_table\n    WHERE complicated_condition = \'1\'\n}\n</code></pre>\n'}, {'answer_id': 116759, 'author': 'newtonapple', 'author_id': 1376, 'author_profile': 'https://Stackoverflow.com/users/1376', 'pm_score': 5, 'selected': False, 'text': "<h1>module_function</h1>\n\n<p>Module methods that are declared as <em>module_function</em> will create copies of themselves as <strong>private</strong> instance methods in the class that includes the Module:</p>\n\n<pre><code>module M\n  def not!\n    'not!'\n  end\n  module_function :not!\nend\n\nclass C\n  include M\n\n  def fun\n    not!\n  end\nend\n\nM.not!     # =&gt; 'not!\nC.new.fun  # =&gt; 'not!'\nC.new.not! # =&gt; NoMethodError: private method `not!' called for #&lt;C:0x1261a00&gt;\n</code></pre>\n\n<p>If you use <em>module_function</em> without any arguments, then any module methods that comes after the module_function statement will automatically become module_functions themselves.</p>\n\n<pre><code>module M\n  module_function\n\n  def not!\n    'not!'\n  end\n\n  def yea!\n    'yea!'\n  end\nend\n\n\nclass C\n  include M\n\n  def fun\n    not! + ' ' + yea!\n  end\nend\nM.not!     # =&gt; 'not!'\nM.yea!     # =&gt; 'yea!'\nC.new.fun  # =&gt; 'not! yea!'\n</code></pre>\n"}, {'answer_id': 224276, 'author': 'Justin Love', 'author_id': 30203, 'author_profile': 'https://Stackoverflow.com/users/30203', 'pm_score': 4, 'selected': False, 'text': '<p><code>Class.new()</code></p>\n\n<p>Create a new class at run time.  The argument can be a class to derive from, and the block is the class body.  You might also want to look at <code>const_set/const_get/const_defined?</code> to get your new class properly registered, so that <code>inspect</code> prints out a name instead of a number.</p>\n\n<p>Not something you need every day, but quite handy when you do.</p>\n'}, {'answer_id': 327208, 'author': 'Dustin', 'author_id': 39975, 'author_profile': 'https://Stackoverflow.com/users/39975', 'pm_score': 2, 'selected': False, 'text': '<p>Ruby has a <a href="http://gd.tuwien.ac.at/languages/scheme/tutorial-dsitaram/t-y-scheme-Z-H-14.html#%_sec_13.1" rel="nofollow noreferrer">call/cc</a> mechanism allowing one to freely hop up and down the stack.</p>\n\n<p>Simple example follows.  This is certainly not how one would multiply a sequence in ruby, but it demonstrates how one might use call/cc to reach up the stack to short-circuit an algorithm.  In this case, we\'re recursively multiplying a list of numbers until we either have seen every number or we see zero (the two cases where we know the answer).  In the zero case, we can be arbitrarily deep in the list and terminate.</p>\n\n<pre><code>#!/usr/bin/env ruby\n\ndef rprod(k, rv, current, *nums)\n  puts "#{rv} * #{current}"\n  k.call(0) if current == 0 || rv == 0\n  nums.empty? ? (rv * current) : rprod(k, rv * current, *nums)\nend\n\ndef prod(first, *rest)\n  callcc { |k| rprod(k, first, *rest) }\nend\n\nputs "Seq 1:  #{prod(1, 2, 3, 4, 5, 6)}"\nputs ""\nputs "Seq 2:  #{prod(1, 2, 0, 3, 4, 5, 6)}"\n</code></pre>\n\n<p>You can see the output here:</p>\n\n<p><a href="http://codepad.org/Oh8ddh9e" rel="nofollow noreferrer">http://codepad.org/Oh8ddh9e</a></p>\n\n<p>For a more complex example featuring continuations moving the other direction on the stack, read the source to <a href="http://www.ruby-doc.org/stdlib/libdoc/generator/rdoc/index.html" rel="nofollow noreferrer">Generator</a>.  </p>\n'}, {'answer_id': 474888, 'author': 'Bo Jeanes', 'author_id': 56690, 'author_profile': 'https://Stackoverflow.com/users/56690', 'pm_score': 6, 'selected': False, 'text': '<p>One of the cool things about ruby is that you can call methods and run code in places other languages would frown upon, such as in method or class definitions.</p>\n\n<p>For instance, to create a class that has an unknown superclass until run time, i.e. is random, you could do the following:</p>\n\n<pre><code>class RandomSubclass &lt; [Array, Hash, String, Fixnum, Float, TrueClass].sample\n\nend\n\nRandomSubclass.superclass # could output one of 6 different classes.\n</code></pre>\n\n<p>This uses the 1.9 <code>Array#sample</code> method (in 1.8.7-only, see <code>Array#choice</code>), and the example is pretty contrived but you can see the power here. </p>\n\n<p>Another cool example is the ability to put default parameter values that are non fixed (like other languages often demand):</p>\n\n<pre><code>def do_something_at(something, at = Time.now)\n   # ...\nend\n</code></pre>\n\n<p>Of course the problem with the first example is that it is evaluated at definition time, not call time. So, once a superclass has been chosen, it stays that superclass for the remainder of the program. </p>\n\n<p>However, in the second example, each time you call <code>do_something_at</code>, the <code>at</code> variable will be the time that the method was called (well, very very close to it)</p>\n'}, {'answer_id': 827932, 'author': 'Chirantan', 'author_id': 45942, 'author_profile': 'https://Stackoverflow.com/users/45942', 'pm_score': 2, 'selected': False, 'text': "<pre><code>class A\n\n  private\n\n  def my_private_method\n    puts 'private method called'\n  end\nend\n\na = A.new\na.my_private_method # Raises exception saying private method was called\na.send :my_private_method # Calls my_private_method and prints private method called'\n</code></pre>\n"}, {'answer_id': 1061004, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Short inject, like such:</p>\n\n<p><a href="http://weblog.raganwald.com/2008/02/1100inject.html" rel="nofollow noreferrer">Sum of range:</a></p>\n\n<pre><code>(1..10).inject(:+)\n=&gt; 55\n</code></pre>\n'}, {'answer_id': 1061835, 'author': 'August Lilleaas', 'author_id': 26051, 'author_profile': 'https://Stackoverflow.com/users/26051', 'pm_score': 5, 'selected': False, 'text': '<p>Hashes with default values! An array in this case.</p>\n\n<pre><code>parties = Hash.new {|hash, key| hash[key] = [] }\nparties["Summer party"]\n# =&gt; []\n\nparties["Summer party"] &lt;&lt; "Joe"\nparties["Other party"] &lt;&lt; "Jane"\n</code></pre>\n\n<p>Very useful in metaprogramming.</p>\n'}, {'answer_id': 1140464, 'author': 'Ropez', 'author_id': 137627, 'author_profile': 'https://Stackoverflow.com/users/137627', 'pm_score': 3, 'selected': False, 'text': "<p>I find this useful in some scripts. It makes it possible to use environment variables directly, like in shell scripts and Makefiles. Environment variables are used as fall-back for undefined Ruby constants.</p>\n\n<pre><code>&gt;&gt; class &lt;&lt;Object\n&gt;&gt;  alias :old_const_missing :const_missing\n&gt;&gt;  def const_missing(sym)\n&gt;&gt;   ENV[sym.to_s] || old_const_missing(sym)\n&gt;&gt;  end\n&gt;&gt; end\n=&gt; nil\n\n&gt;&gt; puts SHELL\n/bin/zsh\n=&gt; nil\n&gt;&gt; TERM == 'xterm'\n=&gt; true\n</code></pre>\n"}, {'answer_id': 1224534, 'author': 'horseyguy', 'author_id': 66725, 'author_profile': 'https://Stackoverflow.com/users/66725', 'pm_score': 4, 'selected': False, 'text': '<p>create an array of consecutive numbers:</p>\n\n<pre><code>x = [*0..5]\n</code></pre>\n\n<p>sets x to [0, 1, 2, 3, 4, 5]</p>\n'}, {'answer_id': 1540615, 'author': 'Jordan Running', 'author_id': 179125, 'author_profile': 'https://Stackoverflow.com/users/179125', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m late to the party, but:</p>\n\n<p>You can easily take two equal-length arrays and turn them into a hash with one array supplying the keys and the other the values:</p>\n\n<pre><code>a = [:x, :y, :z]\nb = [123, 456, 789]\n\nHash[a.zip(b)]\n# =&gt; { :x =&gt; 123, :y =&gt; 456, :z =&gt; 789 }\n</code></pre>\n\n<p>(This works because Array#zip "zips" up the values from the two arrays:</p>\n\n<pre><code>a.zip(b)  # =&gt; [[:x, 123], [:y, 456], [:z, 789]]\n</code></pre>\n\n<p>And Hash[] can take just such an array. I\'ve seen people do this as well:</p>\n\n<pre><code>Hash[*a.zip(b).flatten]  # unnecessary!\n</code></pre>\n\n<p>Which yields the same result, but the splat and flatten are wholly unnecessary--perhaps they weren\'t in the past?)</p>\n'}, {'answer_id': 1817710, 'author': 'horseyguy', 'author_id': 66725, 'author_profile': 'https://Stackoverflow.com/users/66725', 'pm_score': 5, 'selected': False, 'text': '<p>Use a Range object as an infinite lazy list:</p>\n\n<pre><code>Inf = 1.0 / 0\n\n(1..Inf).take(5) #=&gt; [1, 2, 3, 4, 5]\n</code></pre>\n\n<p>More info here: <a href="http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/" rel="nofollow noreferrer">http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/</a></p>\n'}, {'answer_id': 1941479, 'author': 'EmFi', 'author_id': 186039, 'author_profile': 'https://Stackoverflow.com/users/186039', 'pm_score': 5, 'selected': False, 'text': '<p>Boolean operators on non boolean values.</p>\n\n<p><code>&amp;&amp;</code> and <code>||</code> </p>\n\n<p>Both return the value of the last expression evaluated.</p>\n\n<p>Which is why the <code>||=</code> will update the variable with the value returned expression on the right side if the variable is undefined. This is not explicitly documented, but common knowledge.</p>\n\n<p>However the <code>&amp;&amp;=</code> isn\'t quite so widely known about.</p>\n\n<pre><code>string &amp;&amp;= string + "suffix"\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>if string\n  string = string + "suffix"\nend\n</code></pre>\n\n<p>It\'s very handy for destructive operations that should not proceed if the variable is undefined.</p>\n'}, {'answer_id': 1992744, 'author': 'minaguib', 'author_id': 241953, 'author_profile': 'https://Stackoverflow.com/users/241953', 'pm_score': 2, 'selected': False, 'text': '<p>James A. Rosen\'s tip is cool ([*items].each), but I find that it destroys hashes:</p>\n\n<pre><code>irb(main):001:0&gt; h = {:name =&gt; "Bob"}\n=&gt; {:name=&gt;"Bob"}\nirb(main):002:0&gt; [*h]\n=&gt; [[:name, "Bob"]]\n</code></pre>\n\n<p>I prefer this way of handling the case when I accept a list of things to process but am lenient and allow the caller to supply one:</p>\n\n<pre><code>irb(main):003:0&gt; h = {:name =&gt; "Bob"}\n=&gt; {:name=&gt;"Bob"}\nirb(main):004:0&gt; [h].flatten\n=&gt; [{:name=&gt;"Bob"}]\n</code></pre>\n\n<p>This can be combined with a method signature like so nicely:</p>\n\n<pre><code>def process(*entries)\n  [entries].flatten.each do |e|\n    # do something with e\n  end\nend\n</code></pre>\n'}, {'answer_id': 1992828, 'author': 'minaguib', 'author_id': 241953, 'author_profile': 'https://Stackoverflow.com/users/241953', 'pm_score': 4, 'selected': False, 'text': '<p>The "ruby" binary (at least MRI\'s) supports a lot of the switches that made perl one-liners quite popular.</p>\n\n<p>Significant ones:</p>\n\n<ul>\n<li>-n Sets up an outer loop with just "gets" - which magically works with given filename or STDIN, setting each read line in $_</li>\n<li>-p Similar to -n but with an automatic <code>put</code>s at the end of each loop iteration</li>\n<li>-a Automatic call to .split on each input line, stored in $F</li>\n<li>-i In-place edit input files</li>\n<li>-l Automatic call to .chomp on input</li>\n<li>-e Execute a piece of code</li>\n<li>-c Check source code</li>\n<li>-w With warnings</li>\n</ul>\n\n<p>Some examples:</p>\n\n<pre><code># Print each line with its number:\nruby -ne \'print($., ": ", $_)\' &lt; /etc/irbrc\n\n# Print each line reversed:\nruby -lne \'puts $_.reverse\' &lt; /etc/irbrc\n\n# Print the second column from an input CSV (dumb - no balanced quote support etc):\nruby -F, -ane \'puts $F[1]\' &lt; /etc/irbrc\n\n# Print lines that contain "eat"\nruby -ne \'puts $_ if /eat/i\' &lt; /etc/irbrc\n\n# Same as above:\nruby -pe \'next unless /eat/i\' &lt; /etc/irbrc\n\n# Pass-through (like cat, but with possible line-end munging):\nruby -p -e \'\' &lt; /etc/irbrc\n\n# Uppercase all input:\nruby -p -e \'$_.upcase!\' &lt; /etc/irbrc\n\n# Same as above, but actually write to the input file, and make a backup first with extension .bak - Notice that inplace edit REQUIRES input files, not an input STDIN:\nruby -i.bak -p -e \'$_.upcase!\' /etc/irbrc\n</code></pre>\n\n<p>Feel free to google "ruby one-liners" and "perl one-liners" for tons more usable and practical examples.  It essentially allows you to use ruby as a fairly powerful replacement to awk and sed.</p>\n'}, {'answer_id': 2132820, 'author': 'Trevoke', 'author_id': 234025, 'author_profile': 'https://Stackoverflow.com/users/234025', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Auto-vivifying hashes in Ruby</strong></p>\n\n<pre><code>def cnh # silly name "create nested hash"\n  Hash.new {|h,k| h[k] = Hash.new(&amp;h.default_proc)}\nend\nmy_hash = cnh\nmy_hash[1][2][3] = 4\nmy_hash # =&gt; { 1 =&gt; { 2 =&gt; { 3 =&gt;4 } } }\n</code></pre>\n\n<p>This can just be damn handy.</p>\n'}, {'answer_id': 2340767, 'author': 'sickill', 'author_id': 264409, 'author_profile': 'https://Stackoverflow.com/users/264409', 'pm_score': 3, 'selected': False, 'text': '<p><code>Fixnum#to_s(base)</code> can be really useful in some case. One such case is generating random (pseudo)unique tokens by converting random number to string using base of 36.</p>\n\n<p>Token of length 8:</p>\n\n<pre><code>rand(36**8).to_s(36) =&gt; "fmhpjfao"\nrand(36**8).to_s(36) =&gt; "gcer9ecu"\nrand(36**8).to_s(36) =&gt; "krpm0h9r"\n</code></pre>\n\n<p>Token of length 6:</p>\n\n<pre><code>rand(36**6).to_s(36) =&gt; "bvhl8d"\nrand(36**6).to_s(36) =&gt; "lb7tis"\nrand(36**6).to_s(36) =&gt; "ibwgeh"\n</code></pre>\n'}, {'answer_id': 2379114, 'author': 'Fabiano Soriani', 'author_id': 250019, 'author_profile': 'https://Stackoverflow.com/users/250019', 'pm_score': 2, 'selected': False, 'text': '<p>I just <em>love</em> the inline keyword <strong>rescue</strong> like this:<br>\n<strong>EDITED EXAMPLE:</strong></p>\n\n<pre><code>@user #=&gt; nil (but I did\'t know)\n@user.name rescue "Unknown"\nlink_to( d.user.name, url_user( d.user.id, d.user.name)) rescue \'Account removed\'\n</code></pre>\n\n<p>This avoid breaking my App and is way better than the feature released at Rails <em>.try()</em></p>\n'}, {'answer_id': 2792840, 'author': 'haoqi', 'author_id': 131492, 'author_profile': 'https://Stackoverflow.com/users/131492', 'pm_score': 1, 'selected': False, 'text': '<pre><code>@user #=&gt; nil (but I did\'t know)\n@user.name rescue "Unknown"\n</code></pre>\n'}, {'answer_id': 2911455, 'author': 'Judson', 'author_id': 349582, 'author_profile': 'https://Stackoverflow.com/users/349582', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m a fan of:</p>\n\n<pre><code>%w{An Array of strings} #=&gt; ["An", "Array", "of", "Strings"]\n</code></pre>\n\n<p>It\'s sort of funny how often that\'s useful.</p>\n'}, {'answer_id': 3054688, 'author': 'Konstantin Haase', 'author_id': 302187, 'author_profile': 'https://Stackoverflow.com/users/302187', 'pm_score': 6, 'selected': False, 'text': '<p>Wow, no one mentioned the flip flop operator:</p>\n\n<pre><code>1.upto(100) do |i|\n  puts i if (i == 3)..(i == 15)\nend\n</code></pre>\n'}, {'answer_id': 3341493, 'author': 'mhd', 'author_id': 38515, 'author_profile': 'https://Stackoverflow.com/users/38515', 'pm_score': 2, 'selected': False, 'text': '<p><strong>each_with_index</strong> method for any enumarable object ( array,hash,etc.) perhaps? </p>\n\n<pre><code>myarray = ["la", "li", "lu"]\nmyarray.each_with_index{|v,idx| puts "#{idx} -&gt; #{v}"}\n\n#result:\n#0 -&gt; la\n#1 -&gt; li\n#2 -&gt; lu\n</code></pre>\n\n<p>Maybe it\'s more well known than other answers but not that well known for all ruby programmers :)</p>\n'}, {'answer_id': 3823852, 'author': 'horseyguy', 'author_id': 66725, 'author_profile': 'https://Stackoverflow.com/users/66725', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Destructuring an Array</strong></p>\n\n<pre><code>(a, b), c, d = [ [:a, :b ], :c, [:d1, :d2] ]\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>a #=&gt; :a\nb #=&gt; :b\nc #=&gt; :c\nd #=&gt; [:d1, :d2]\n</code></pre>\n\n<p>Using this technique we can use simple assignment to get the exact values we want out of nested array of any depth.</p>\n'}, {'answer_id': 3834838, 'author': 'horseyguy', 'author_id': 66725, 'author_profile': 'https://Stackoverflow.com/users/66725', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Defining a method that accepts any number of parameters and just discards them all</strong></p>\n\n<pre><code>def hello(*)\n    super\n    puts "hello!"\nend\n</code></pre>\n\n<p>The above <code>hello</code> method only needs to <code>puts</code> <code>"hello"</code> on the screen and call <code>super</code> - but since the superclass <code>hello</code> defines parameters it has to as well - however since it doesn\'t actually need to use the parameters itself - it doesn\'t have to give them a name.</p>\n'}, {'answer_id': 4139641, 'author': 'Kelvin', 'author_id': 498594, 'author_profile': 'https://Stackoverflow.com/users/498594', 'pm_score': 2, 'selected': False, 'text': '<p>Calling a method defined anywhere in the inheritance chain, even if overridden</p>\n\n<p>ActiveSupport\'s objects sometimes masquerade as built-in objects.</p>\n\n<pre>\nrequire \'active_support\'\ndays = 5.days\ndays.class  #=> Fixnum\ndays.is_a?(Fixnum)  #=> true\nFixnum === days  #=> false (huh? what are you really?)\nObject.instance_method(:class).bind(days).call  #=> ActiveSupport::Duration (aha!)\nActiveSupport::Duration === days  #=> true\n</pre>\n\n<p>The above, of course, relies on the fact that active_support doesn\'t redefine Object#instance_method, in which case we\'d really be up a creek. Then again, we could always save the return value of Object.instance_method(:class) before any 3rd party library is loaded.</p>\n\n<p>Object.instance_method(...) returns an UnboundMethod which you can then bind to an instance of that class. In this case, you can bind it to any instance of Object (subclasses included).</p>\n\n<p>If an object\'s class includes modules, you can also use the UnboundMethod from those modules.</p>\n\n<pre>\nmodule Mod\n  def var_add(more); @var+more; end\nend\nclass Cla\n  include Mod\n  def initialize(var); @var=var; end\n  # override\n  def var_add(more); @var+more+more; end\nend\ncla = Cla.new(\'abcdef\')\ncla.var_add(\'ghi\')  #=> "abcdefghighi"\nMod.instance_method(:var_add).bind(cla).call(\'ghi\')  #=> "abcdefghi"\n</pre>\n\n<p>This even works for singleton methods that override an instance method of the class the object belongs to.</p>\n\n<pre>\nclass Foo\n  def mymethod; \'original\'; end\nend\nfoo = Foo.new\nfoo.mymethod  #=> \'original\'\ndef foo.mymethod; \'singleton\'; end\nfoo.mymethod  #=> \'singleton\'\nFoo.instance_method(:mymethod).bind(foo).call  #=> \'original\'\n\n# You can also call #instance method on singleton classes:\nclass &lt;&lt; foo; self; end.instance_method(:mymethod).bind(foo).call  #=> \'singleton\'\n</pre>\n'}, {'answer_id': 4294367, 'author': 'Ramiz Uddin', 'author_id': 134743, 'author_profile': 'https://Stackoverflow.com/users/134743', 'pm_score': 2, 'selected': False, 'text': '<h2>Multiple return values</h2>\n\n<pre><code>def getCostAndMpg\n    cost = 30000  # some fancy db calls go here\n    mpg = 30\n    return cost,mpg\nend\nAltimaCost, AltimaMpg = getCostAndMpg\nputs "AltimaCost = #{AltimaCost}, AltimaMpg = #{AltimaMpg}"\n</code></pre>\n\n<h2>Parallel Assignment</h2>\n\n<pre><code>i = 0\nj = 1\nputs "i = #{i}, j=#{j}"\ni,j = j,i\nputs "i = #{i}, j=#{j}"\n</code></pre>\n\n<h2>Virtual Attributes</h2>\n\n<pre><code>class Employee &lt; Person\n  def initialize(fname, lname, position)\n    super(fname,lname)\n    @position = position\n  end\n  def to_s\n     super + ", #@position"\n  end\n  attr_writer :position\n  def etype\n     if @position == "CEO" || @position == "CFO"\n         "executive"\n     else\n         "staff"\n     end\n  end\nend\nemployee = Employee.new("Augustus","Bondi","CFO")\nemployee.position = "CEO"\nputs employee.etype    =&gt;  executive\nemployee.position = "Engineer"\nputs employee.etype    =&gt;  staff\n</code></pre>\n\n<h2>method_missing - a wonderful idea</h2>\n\n<p><em>(In most languages when a method cannot be found and error is thrown and your program stops. In ruby you can actually catch those errors and perhaps do something intelligent with the situation)</em></p>\n\n<pre><code>class MathWiz\n  def add(a,b) \n    return a+b\n  end\n  def method_missing(name, *args)\n    puts "I don\'t know the method #{name}"\n  end\nend\nmathwiz = MathWiz.new\nputs mathwiz.add(1,4)\nputs mathwiz.subtract(4,2)\n</code></pre>\n\n<blockquote>\n  <p>5</p>\n  \n  <p>I don\'t know the method subtract</p>\n  \n  <p>nil</p>\n</blockquote>\n'}, {'answer_id': 5333299, 'author': 'Aaa', 'author_id': 636053, 'author_profile': 'https://Stackoverflow.com/users/636053', 'pm_score': 2, 'selected': False, 'text': '<p>There are some aspects of symbol literals that people should know. One case solved by special symbol literals is when you need to create a symbol whose name causes a syntax error for some reason with the normal symbol literal syntax:</p>\n\n<pre><code>:\'class\'\n</code></pre>\n\n<p>You can also do symbol interpolation. In the context of an accessor, for example:</p>\n\n<pre><code>define_method :"#{name}=" do |value|\n  instance_variable_set :"@#{name}", value\nend\n</code></pre>\n'}, {'answer_id': 6037067, 'author': 'J-_-L', 'author_id': 169793, 'author_profile': 'https://Stackoverflow.com/users/169793', 'pm_score': 3, 'selected': False, 'text': '<p>To combine multiple regexes with <code>|</code>, you can use</p>\n\n<pre><code>Regexp.union /Ruby\\d/, /test/i, "cheat"\n</code></pre>\n\n<p>to create a Regexp similar to:</p>\n\n<pre><code>/(Ruby\\d|[tT][eE][sS][tT]|cheat)/\n</code></pre>\n'}, {'answer_id': 6279466, 'author': 'Szymon Jeż', 'author_id': 408011, 'author_profile': 'https://Stackoverflow.com/users/408011', 'pm_score': 3, 'selected': False, 'text': "<pre><code>private unless Rails.env == 'test'\n# e.g. a bundle of methods you want to test directly\n</code></pre>\n\n<p>Looks like a cool and (in some cases) nice/useful hack/feature of Ruby.</p>\n"}, {'answer_id': 8933705, 'author': 'Alex D', 'author_id': 960828, 'author_profile': 'https://Stackoverflow.com/users/960828', 'pm_score': 2, 'selected': False, 'text': '<p>I just read all the answers... one notable omission was destructuring assignment:</p>\n\n<pre><code>&gt; (a,b),c = [[1,2],3]\n=&gt; [[1,2],3]\n&gt; a\n=&gt; 1\n</code></pre>\n\n<p>It also works for block parameters. This is useful when you have nested arrays, each element of which represents something distinct. Instead of writing code like "array[0][1]", you can break that nested array down and give a descriptive name to each element, in a single line of code.</p>\n'}, {'answer_id': 9214173, 'author': 'iblue', 'author_id': 773690, 'author_profile': 'https://Stackoverflow.com/users/773690', 'pm_score': 1, 'selected': False, 'text': '<h2>The sprintf shortcut</h2>\n\n<p>My favourite ruby feature. Syntax is <code>format_string % argument</code></p>\n\n<pre><code>"%04d"  % 1         # =&gt; "0001"\n"%0.2f" % Math::PI  # =&gt; "3.14"\n</code></pre>\n\n<p>Works as well for arrays (<code>format_string % array_of_arguments</code>)</p>\n\n<pre><code>"%.2f %.3f %.4f" % ([Math::PI]*3) \n# =&gt; "3.14 3.142 3.1416"\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/63998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7754/']