Best ruby questions in January 2012

Why a = a is nil in Ruby?

14 votes

I watched this video today, and I would like to know why the code a = a will be evaluated to nil if a is not defined.

I also found this is also happen when using parallel assign.

What is the reason that ruby evaluated those expression to nil?

brianhsu@USBGentoo ~ $ irb
irb(main):001:0> a = a
=> nil
irb(main):002:0> b = c = q = c 
=> nil
irb(main):003:0> 

Because Ruby interpreter initialize local variable with nil when it sees an assignment to it. It initialize variable before it execute the line of code so the assignment expression may not even be reachable (as in example below). This mean your code initialize a with nil and then expression a = nil will evaluate to the right hand value.

a = 1 if false
a.nil? # => true

The first assignment expression is not executed, but a is initialized with nil

Ruby expression evaluation: whitespace matters?

13 votes

Imagine it's Jan 19. This will not be hard if you look at this question today.

Date.today
 => Thu, 19 Jan 2012    # as expected

Date.today + 1
 => Fri, 20 Jan 2012    # as expected

Date.today+1
 => Fri, 20 Jan 2012    # as expected

Date.today +1
 => Thu, 19 Jan 2012    # ?!

What am I missing here?

The difference is that:

Date.today + 1 

is an addition of two numerical values and

Date.today +1 

is a call to the method today with the parameter sg(day of calendar reform) with value +1

The best way to examine this is to monkey patch the original method with debug output included. See this script as example:

require 'date'

class Date

  def self.today(sg=ITALY)
     puts "ITALY default("+sg.to_s+")" if sg==ITALY
     puts sg unless sg==ITALY
     jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg))
     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  end

end

puts "- Addition:"
Date.today + 1
puts "- Parameter:"
Date.today +1

This will print the following console output:

- Addition:
ITALY default(2299161)
- Parameter:
1

12 votes

How can I create an Object in ruby that will be evaluated to false in logical expressions similar to nil?

My intention is to enable nested calls on other Objects where somewhere half way down the chain a value would normally be nil, but allow all the calls to continue - returning my nil-like object instead of nil itself. The object will return itself in response to any received messages that it does not know how to handle and I anticipate that I will need to implement some override methods such as nil?.

For example:

fizz.buzz.foo.bar

If the buzz property of fizz was not available I would return my nil-like object, which would accept calls all the way down to bar returning itself. Ultimately, the statement above should evaluate to false.

Edit:

Based on all the great answers below I have come up with the following:

class NilClass
  attr_accessor :forgiving
  def method_missing(name, *args, &block)
    return self if @forgiving
    super
  end
  def forgive
    @forgiving = true
    yield if block_given?
    @forgiving = false
  end
end

This allows for some dastardly tricks like so:

nil.forgiving {
    hash = {}
    value = hash[:key].i.dont.care.that.you.dont.exist
    if value.nil?
        # great, we found out without checking all its parents too
    else
        # got the value without checking its parents, yaldi
    end
}

Obviously you could wrap this block up transparently inside of some function call/class/module/wherever.

This is a pretty long answer with a bunch of ideas and code samples of how to approach the problem.

try

Rails has a try method that let's you program like that. This is kind of how it's implemented:

class Object
  def try(*args, &b)
    __send__(*a, &b)
  end
end

class NilClass
  def try(*args)
    nil
  end
end

You can program with it like this:

fizz.try(:buzz).try(:foo).try(:bar)

You could conceivably modify this to work a little differently to support a more elegant API:

class Object
  def try(*args)
    if args.length > 0
      method = args.shift
      __send__(method).try(*args)
    else
      self
    end
  end
end

Then you could do:

fizz.try(:buzz, :foo, :bar)

andand

andand uses a more nefarious technique, hacking the fact that you can't directly instantiate NilClass subclasses:

class Object
  def andand
    if self
      self
    else
      Mock.new(self)
    end
  end
end

class Mock < BasicObject
  def initialize(me)
    super()
    @me = me
  end
  def method_missing(*args)
    @me
  end
end

This allows you to program this way:

fizz.andand.buzz.andand.foo.andand.bar

Combine with some fancy rewriting

Again you could expand on this technique:

class Object
  def method_missing(m, *args, &blk)
    if m[0] == '_' and respond_to? m[1..-1]
      Mock.new(self.send(m[1..-1]))
    else
      super
    end
  end
end

class Mock < BasicObject
  def initialize(me)
    super()
    @me = me
  end
  def method_missing(m, *args, &blk)
    if m[-1] == '_'
      @me.send(m[0...-1], *args, &blk) if @me
    else
      @me = @me.send(m, *args, &blk) if @me
      self
    end
  end
end

Allowing for an api like this (I used underscores, but you could use really anything):

fizz._buzz.foo.bum.yum.bar_

Brutal monkey-patching approach

This is really quite nasty, but it allows for an elegant API and doesn't necessarily screw up error reporting in your whole app:

class NilClass
  attr_accessor :complain
  def method_missing(*args)
    if @complain
      super
    else
      self
    end
  end
end
nil.complain = true

Use like this:

nil.complain = false
fizz.buzz.foo.bar
nil.complain = true

Autoloading classes in Ruby without its `autoload`

10 votes

I love the autoload functionality of Ruby; however, it's going away in future versions of Ruby since it was never thread-safe.

So right now I would like to pretend it's already gone and write my code without it, by implementing the lazy-loading mechanism myself. I'd like to implement it in the simplest way possible (I don't care about thread-safety right now). Ruby should allow us to do this.

Let's start by augmenting a class' const_missing:

class Dummy
  def self.const_missing(const)
    puts "const_missing(#{const.inspect})"
    super(const)
  end
end

Ruby will call this special method when we try to reference a constant under "Dummy" that's missing, for instance if we try to reference "Dummy::Hello", it will call const_missing with the Symbol :Hello. This is exactly what we need, so let's take it further:

class Dummy
  def self.const_missing(const)
    if :OAuth == const
      require 'dummy/oauth'
      const_get(const)      # warning: possible endless loop!
    else
      super(const)
    end
  end
end

Now if we reference "Dummy::OAuth", it will require the "dummy/oauth.rb" file which is expected to define the "Dummy::OAuth" constant. There's a possibility of an endless loop when we call const_get (since it can call const_missing internally), but guarding against that is outside the scope of this question.

The big problem is, this whole solution breaks down if there exists a module named "OAuth" in the top-level namespace. Referencing "Dummy::OAuth" will skip its const_missing and just return the "OAuth" from the top-level. Most Ruby implementations will also make a warning about this:

warning: toplevel constant OAuth referenced by Dummy::OAuth

This was reported as a problem way back in 2003 but I couldn't find evidence that the Ruby core team was ever concerned about this. Today, most popular Ruby implementations carry the same behavior.

The problem is that const_missing is silently skipped in favor of a constant in the top-level namespace. This wouldn't happen if "Dummy::OAuth" was declared with Ruby's autoload functionality. Any ideas how to work around this?

This was raised in a Rails ticket some time ago and when I investigated it there appeared to be no way round it. The problem is that Ruby will search the ancestors before calling const_missing and since all classes have Object as an ancestor then any top-level constants will always be found. If you can restrict yourself to only using modules for namespacing then it will work since they do not have Object as an ancestor, e.g:

>> class A; end
>> class B; end
>> B::A
(irb):3: warning: toplevel constant A referenced by B::A

>> B.ancestors
=> [B, Object, Kernel, BasicObject]

>> module C; end
>> module D; end
>> D::C
NameError: uninitialized constant D::C

>> D.ancestors
=> [D]

How can I efficiently scrub Ruby's negative zero float?

8 votes

In Ruby, 0.0 * -1 == -0.0.

I have an application where I multiply a bunch of Float objects with -1, but I don't like the -0.0 in the output, since it's confusing.

Is there a smart way of making Float#to_s output 0.0 instead of -0.0?

I'm completely fine with running every Float object through some kind of scrubber/helper method, but the following just tends to make me even more confused:

def clean_output(amount)
  if amount.zero?
    0.0
  else
    amount
  end
end

UPDATE:

To be more precise on what I'm looking for, I want a solution that I can run on a whole bunch of floats, some of which will be negative, some positive. The negative ones should remain negative unless they're negative zeroes, i.e. -0.0.

Examples:

clean_output(-0.0) #=>  0.0
clean_output(-3.0) #=> -3.0
clean_output(3.0)  #=>  3.0

If the code you wrote confuses you then this ought to really bend your mind:

def clean_output(amount)
  amount.zero? && 0.0 || amount
end

With some proof:

irb(main):005:0> f = 0.0
=> 0.0
irb(main):006:0> f.zero? && 0.0 || f
=> 0.0
irb(main):007:0> f = -0.0
=> -0.0
irb(main):008:0> f.zero? && 0.0 || f
=> 0.0
irb(main):009:0> f=1.0
=> 1.0
irb(main):010:0> f.zero? && 0.0 || f
=> 1.0

I don't like using nonzero? because its use-case is a bit confused. It's part of Numeric but the docs show it used as part of Comparable with the <=> operator. Plus, I'd rather test for a zero condition for this purpose because it seems more straightforward.

And, though the OP's code might appear verbose, this is another of those cases where premature optimization doesn't pay off:

require 'benchmark'

def clean_output(amount)
  if amount.zero?
    0.0
  else
    amount
  end
end

def clean_output2(amount)
  amount.zero? && 0.0 || amount
end

def clean_output3(value)
  value + 0
end

class Numeric
  def clean_to_s
    (nonzero? || abs).to_s
  end
end


n = 5_000_000
Benchmark.bm(14) do |x|
  x.report( "clean_output:"  ) { n.times { a = clean_output(-0.0)  } }
  x.report( "clean_output2:" ) { n.times { a = clean_output2(-0.0) } }
  x.report( "clean_output3:" ) { n.times { a = clean_output3(-0.0) } }
  x.report( "clean_to_s:"    ) { n.times { a = 0.0.clean_to_s      } }
end

And the results:

ruby test.rb 
                    user     system      total        real
clean_output:   2.120000   0.000000   2.120000 (  2.127556)
clean_output2:  2.230000   0.000000   2.230000 (  2.222796)
clean_output3:  2.530000   0.000000   2.530000 (  2.534189)
clean_to_s:     7.200000   0.010000   7.210000 (  7.200648)

ruby test.rb 
                    user     system      total        real
clean_output:   2.120000   0.000000   2.120000 (  2.122890)
clean_output2:  2.200000   0.000000   2.200000 (  2.203456)
clean_output3:  2.540000   0.000000   2.540000 (  2.533085)
clean_to_s:     7.200000   0.010000   7.210000 (  7.204332)

I added a version without the to_s. These were run on my laptop, which is several years old, which is why the resulting times are higher than the previous tests:

require 'benchmark'

def clean_output(amount)
  if amount.zero?
    0.0
  else
    amount
  end
end

def clean_output2(amount)
  amount.zero? && 0.0 || amount
end

def clean_output3(value)
  value + 0
end

class Numeric
  def clean_to_s
    (nonzero? || abs).to_s
  end

  def clean_no_to_s
    nonzero? || abs
  end

end


n = 5_000_000
Benchmark.bm(14) do |x|
  x.report( "clean_output:"  ) { n.times { a = clean_output(-0.0)  } }
  x.report( "clean_output2:" ) { n.times { a = clean_output2(-0.0) } }
  x.report( "clean_output3:" ) { n.times { a = clean_output3(-0.0) } }
  x.report( "clean_to_s:"    ) { n.times { a = -0.0.clean_to_s     } }
  x.report( "clean_no_to_s:" ) { n.times { a = -0.0.clean_no_to_s  } }
end

And the results:

ruby test.rb 
                    user     system      total        real
clean_output:   3.030000   0.000000   3.030000 (  3.028541)
clean_output2:  2.990000   0.010000   3.000000 (  2.992095)
clean_output3:  3.610000   0.000000   3.610000 (  3.610988)
clean_to_s:     8.710000   0.010000   8.720000 (  8.718266)
clean_no_to_s:  5.170000   0.000000   5.170000 (  5.170987)

ruby test.rb 
                    user     system      total        real
clean_output:   3.050000   0.000000   3.050000 (  3.050175)
clean_output2:  3.010000   0.010000   3.020000 (  3.004055)
clean_output3:  3.520000   0.000000   3.520000 (  3.525969)
clean_to_s:     8.710000   0.000000   8.710000 (  8.710635)
clean_no_to_s:  5.140000   0.010000   5.150000 (  5.142462)

To sort out what was slowing down non_zero?:

require 'benchmark'

n = 5_000_000
Benchmark.bm(9) do |x|
  x.report( "nonzero?:" ) { n.times { -0.0.nonzero? } }
  x.report( "abs:"      ) { n.times { -0.0.abs      } }
  x.report( "to_s:"     ) { n.times { -0.0.to_s     } }
end

With the results:

ruby test.rb 
               user     system      total        real
nonzero?:  2.750000   0.000000   2.750000 (  2.754931)
abs:       2.570000   0.010000   2.580000 (  2.569420)
to_s:      4.690000   0.000000   4.690000 (  4.687808)

ruby test.rb 
               user     system      total        real
nonzero?:  2.770000   0.000000   2.770000 (  2.767523)
abs:       2.570000   0.010000   2.580000 (  2.569757)
to_s:      4.670000   0.000000   4.670000 (  4.678333)

What inspired Ruby's =begin .. =end comment block syntax?

8 votes

I know that a lot of Ruby was inspired by Perl (e.g. STDIN as a global constant) or Unix shell (e.g. the <<END heredoc syntax). But I don't know where the block comment syntax comes from. The syntax:

=begin
This is a comment line
it explains that the next line of code displays 
a welcome message
=end

Where does this come from? My knowledge of Perl is sketchy. Is it Perl?

yes, this is Perl

Perl uses

=begin
This is a comment line
it explains that the next line of code displays 
a welcome message
=cut

have a look here: http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(syntax)#Comments

How to write negative loop in ruby like for(i=index; i >= 0; i --)

8 votes

I am new with ruby. wish to know how to write following loop in ruby.

var index=25; 

for (i = index; i >= 0; i--) { 
    print i;
}

Thanks in advance

There are many ways to perform a decrementing loop in Ruby:

First way:

for i in (10).downto(0)
   puts i 
end

Second way:

index = 10 # any value
index.downto(0) do |i|
  puts i
end

Third way:

i = index
until i > 0
  i -= 1
  puts i
end

Converting String "2½" (two and a half) into 2.5

8 votes

Right now I'm building a small app that imports data from a spreadsheet and due to the nature of the original entry, there is a string being read in that has values such as 8½, 2½, etc.

My goal with a simple function is to convert 2½ into float 2.5, for example.

I've tried the .to_f method but that has left me with a weird value of 2.02½.

Any insight or suggestions here would be very much appreciated!

Unicode only supports a small number of vulgar fractions so a simple lookup table will do the trick:

# You might want to double check this mapping
vulgar_to_float = {
    "\u00BC" => 1.0 / 4.0,
    "\u00BD" => 1.0 / 2.0,
    "\u00BE" => 3.0 / 4.0,
    "\u2150" => 1.0 / 7.0,
    "\u2151" => 1.0 / 9.0,
    "\u2152" => 1.0 /10.0,
    "\u2153" => 1.0 / 3.0,
    "\u2154" => 2.0 / 3.0,
    "\u2155" => 1.0 / 5.0,
    "\u2156" => 2.0 / 5.0,
    "\u2157" => 3.0 / 5.0,
    "\u2158" => 4.0 / 5.0,
    "\u2159" => 1.0 / 6.0,
    "\u215A" => 5.0 / 6.0,
    "\u215B" => 1.0 / 8.0,
    "\u215C" => 3.0 / 8.0,
    "\u215D" => 5.0 / 8.0,
    "\u215E" => 7.0 / 8.0,
    "\u2189" => 0.0 / 3.0,
}

Then, a little bit of regex wrangling to pull your "number" apart:

s = "2½"
_, int_part, vulgar_part = *s.match(/(\d+)?(\D+)?/)

And finally, put them together taking care to properly deal with possible nils from the regex:

float_version = int_part.to_i + vulgar_to_float[vulgar_part].to_f

Remember that nil.to_i is 0 and nil.to_f is 0.0.

Where can I install gems from when rubygems.org is down?

6 votes

Currently Rubygems.org is down - the website reports an error, and a few gem install tasks are returning 500 errors.

Is there a mirror / backup source of gem files, or is rubygems.org essentially a single point of failure within the ruby gem installation process ?

As per several folks on Twitter, add this to your Gemfile:

source 'http://production.cf.rubygems.org'

Also, if you're not using Bundler then just run:

$ gem source -a 'http://production.cf.rubygems.org'

For the record, the folks on Twitter include:

laizer, iltempo, and jimneath. Major thanks to them for saving my morning :)

Singleton vs. Monostate Pattern in Ruby

6 votes

Suppose a class needs to load an external library which takes some time to load and thus should be loaded only once. Two natural solutions to this would be to use the singleton pattern or the monostate pattern. Is there any advantage to either of these solutions in this particular context in Ruby?

For example:

# Using a Singleton class
require 'singleton'

class Parser
  include Singleton

    def initialize
      @parser = load_external_library
    end

    def parse(sentence)
      @parser.parse(sentence)
    end
end

# Then calling using...
Parser.instance.parse(sentence)

Versus:

# Using a Monostate class

class Parser
    def self.parse(sentence)
      @@parser ||= load_external_library
      @@parser.parse(sentence)
    end
end

# Then calling using...
Parser.parse(sentence)

Since the second syntax is much cleaner, are there any advantages to using the Singleton in Ruby?

The singleton pattern structurally enforces the fact that you can never have more than one instance of a class at a time, and it is obvious to the developers that they are dealing with a singleton.

The monostate enforces the behavior of a singleton without the structure of the monostate.

You might find situations where you still need instance data. Therefore a monostate would be better. You can create the instance, use methods to affect instance data and still have access to the static data. With a singleton, you cannot have instance data.

Besides, If you plan on deriving classes from the singleton and you want those classes to be singletons, your better choice is monostate. That’s because all classes derived from a monostate are monostates. Classes derived singleton classes are not singletons by default. You would have to add the static method and attribute to each derived class.

Is there a hook for when anonymous classes are assigned to a constant?

6 votes

I've been practicing some Ruby meta-programming recently, and was wondering about assigning anonymous classes to constants.

In Ruby, it is possible to create an anonymous class as follows:

anonymous_class = Class.new  # => #<Class:0x007f9c5afb21d0>

New instances of this class can be created:

an_instance = anonymous_class.new # => #<#<Class:0x007f9c5afb21d0>:0x007f9c5afb0330>

Now, when the anonymous class is assigned to a constant, the class now has a proper name:

Foo = anonymous_class # => Foo

And the previously created instance is now also an instance of that class:

an_instance # => #<Foo:0x007f9c5afb0330>

My question: Is there a hook method for the moment when an anonymous class is assigned to a constant?

There are many hooks methods in Ruby, but I couldn't find this one.

Let's take a look at how constant assignment works internally. The code that follows is extracted from a source tarball of ruby-1.9.3-p0. First we look at the definition of the VM instruction setconstant (which is used to assign constants):

# /insns.def, line 239
DEFINE_INSN
setconstant
(ID id)
(VALUE val, VALUE cbase)
()
{
  vm_check_if_namespace(cbase);
  rb_const_set(cbase, id, val);
  INC_VM_STATE_VERSION();
}

No chance to place a hook in vm_check_if_namespace or INC_VM_STATE_VERSION here. So we look at rb_const_set (variable.c:1886), the function that is called everytime a constant is assigned:

# /variable.c, line 1886
void
rb_const_set(VALUE klass, ID id, VALUE val)
{
    rb_const_entry_t *ce;
    VALUE visibility = CONST_PUBLIC;

    # ...

    check_before_mod_set(klass, id, val, "constant");
    if (!RCLASS_CONST_TBL(klass)) {
      RCLASS_CONST_TBL(klass) = st_init_numtable();
    }
    else {
      # [snip], won't be called on first assignment
    }

    rb_vm_change_state();

    ce = ALLOC(rb_const_entry_t);
    ce->flag = (rb_const_flag_t)visibility;
    ce->value = val;

    st_insert(RCLASS_CONST_TBL(klass), (st_data_t)id, (st_data_t)ce);
}

I removed all the code that was not even called the first time a constant was assigned inside a module. I then looked into all the functions called by this one and didn't find a single point where we could place a hook from Ruby code. This means the hard truth is, unless I missed something, that there is no way to hook a constant assignment (at least in MRI).

Update

To clarify: The anonymous class does not magically get a new name as soon as it is assigned (as noted correctly in Andrew's answer). Rather, the constant name along with the object ID of the class is stored in Ruby's internal constant lookup table. If, after that, the name of the class is requested, it can now be resolved to a proper name (and not just Class:0xXXXXXXXX...).

So the best you can do to react to this assignment is to check the name of the class in a loop of a background worker thread until it is non-nil (which is a huge waste of resources, IMHO).

How to handle translations for an ActiveModel?

6 votes

I am using Rails 3.1.1 and I would like to properly translate error messages for an ActiveModel. I don't know if overwriting the i18n_scope is the right way to solve my problem (or if there are other ways), but the official documentation says:

i18n_scope()

Returns the i18n_scope for the class. Overwrite if you want custom lookup.

... how should I overwtite the i18n_scope?

At this time I am getting a the following "alert":

# Note the 'activemodel' part
translation missing: de.activemodel.errors.models.my_class.attributes.message.blank

# I would like to "map" translations to 'de.activerecord.errors.messages.blank'
# as made for all other ActiveRecord classes in my application

My ActiveModel class is like the following:

class MyClass
  include ActiveModel::Conversion
  include ActiveModel::Validations
  include ActiveModel::Dirty
  extend  ActiveModel::Naming
  extend  ActiveModel::Translation

  validates :name, :presence => true

  ...
end

It should be a class method, by analogy with AR code:

class MyClass
  include ActiveModel ...
  class << self
    def i18n_scope
      :activerecord
    end
  end
end

How do I do element-wise comparison of two arrays?

6 votes

I have two arrays:

a = [1,2,3]
b = [1,4,3]

Is there an element-wise comparison method in Ruby such that I could do something like this:

a == b

returns:

[1,0,1] or something like [TRUE,FALSE,TRUE].

Here's one way that I can think of.

a = [1, 2, 3]
b = [1, 4, 3]

a.zip(b).map { |x, y| x == y } # [true, false, true]

Are Ruby 1.9 regular expressions equally powerful to a context free grammar?

6 votes

I have this regular expression:

regex = %r{\A(?<foo> a\g<foo>a | b\g<foo>b | c)\Z}x

When I test it against several strings, it appears to be as powerful as a context free grammar because it handles the recursion properly.

regex.match("aaacaaa")
# => #<MatchData "aaacaaa" foo:"aaacaaa">
regex.match("aacaa")
# => #<MatchData "aacaa" foo:"aacaa">
regex.match("aabcbaa")
# => #<MatchData "aabcbaa" foo:"aabcbaa">
regex.match("aaacaa")
# => nil

"Fun with Ruby 1.9 Regular Expressions" has an example where he actually arranges all the parts of a regex so that it looks like a context-free grammar as follows:

sentence = %r{ 
    (?<subject>   cat   | dog   | gerbil    ){0} 
    (?<verb>      eats  | drinks| generates ){0} 
    (?<object>    water | bones | PDFs      ){0} 
    (?<adjective> big   | small | smelly    ){0} 

    (?<opt_adj>   (\g<adjective>\s)?     ){0} 

    The\s\g<opt_adj>\g<subject>\s\g<verb>\s\g<opt_adj>\g<object> 
}x

Between his technique for rearranging the parts of the regex, and my example of recursive named capturing groups, does this mean Ruby 1.9 regular expressions have the power equivalent to a context-free grammar?

This is one of the awesome things are the Oniguruma regexp engine used in Ruby 1.9 -- it has the power of a parser, and is not restricted to recognizing regular languages. It has positive and negative lookahead/lookbehind, which even can be used to recognize some languages which are not context-free! Take the following as an example:

regexp = /\A(?<AB>a\g<AB>b|){0}(?=\g<AB>c)a*(?<BC>b\g<BC>c|){1}\Z/

This regexp recognizes strings like "abc", "aabbcc", "aaabbbccc", and so on -- the number of "a", "b", and "c" must be equal, or it will not match.

(One limitation: you can't use named groups in the lookahead and lookbehind.)

Although I haven't peeked under the hood, Oniguruma seems to deal with named groups by simple recursive descent, backing up when something doesn't match. I've observed that it can't deal with left recursion. For example:

irb(main):013:0> regexp = /(?<A>\g<A>a|)/
SyntaxError: (irb):13: never ending recursion: /(?<A>\g<A>a|)/
    from C:/Ruby192/bin/irb:12:in `<main>'

I don't remember my parsing theory very clearly, but I think that a non-deterministic top-down parser like this should be able to parse any context-free language. ("language", not "grammar"; if your grammar has left recursion, you will have to convert it to right recursion.) If that is incorrect, please edit this post.

Ruby: is there a keyword to call a method from within itself (analogous to `super`)?

6 votes

I am wondering: is there a way to call a method from within itself in Ruby without using its name?

If the method was created by some metaprogramming techniques, then calling it by its name may be hard to read. Even for a usually defined method, if you are not sure about a good name for it, or if its name is long, calling it from within itself by some keyword (analogous to super) may be convenient.

You can use Kernel#__method__ that returns the name of the current method as a Symbol. Unlike super it's not a keyword but a regular method so you have to pass it to send method along with required arguments in order to call the method.

Here is what __method__ returns:

obj = Object.new

def obj.foo
  p __method__
end

obj.foo
# => :foo

And here is an example of class method that dynamically defines factorial methods:

class Foo
  def self.define_fact(method_name)
    define_method(method_name) do |n|
      n > 0 ? n * send(__method__, n - 1) : 1
    end
  end
end

f = Foo.new
# puts f.fact(5) 
# => undefined method `fact' for #<Foo:0x8ede45c> (NoMethodError)
Foo.define_fact :fact
puts f.fact(5)
# => 120 

Without __method__ I can't think of any solution that wouldn't involve some kind of eval that is better to avoid if possible.

How to split routes.rb into smaller files

5 votes

Is it possible to split Rails 3.X routes.rb file?

We have so many resources it is difficult to find them. I would like to split at least APP and REST API routes.

Thanks!

You can do that:

routes.rb

require 'application_routes'
require 'rest_api_routes'

lib/application_routes.rb

YourApplication::Application.routes.draw do
  # Application related routes
end

lib/rest_api_routes.rb

YourApplication::Application.routes.draw do
  # REST API related routes
end