Notes posted to Ruby

RSS feed
January 14, 2013 - (>= v1_8_6_287)
0 thanks

Pass a block

While this example is not so obvious on first look what the block passed does, here’s a small explanation:

when the block is passed to this function, the uniqueness is checked based on a value returned by that block.

For example if it’s array of objects with “user_id” method, then this would be:

tasks.uniq{|t| t.user_id } # returns only tasks with unique user_id 
January 13, 2013
0 thanks

Note sure if doco is correct

(Note this was an issue in Ruby 1.9.2, 1.9.3 has been corrected, not sure why the generated doc is still incorrect)

Both exist? and exists? use the same underlying C function

file.c, line 5444

define_filetest_function("exist?", rb_file_exist_p, 1);
define_filetest_function("exists?", rb_file_exist_p, 1);

rb_file_exist_p does an rb_stat call, and just checks for no error.

rb_stat returns the result of a call to fstat, if the passed in value is a IO object, or stat (or your platforms equivalent). Both these return 0 on success, -1 on failure.

So both really just check that the underlying “thing” can respond to “stat” correctly. There are many things in a unix-style filesystem that have a “file” structure, not just traditional files. These functions help when you don’t care what type an entry is, just that it exists.

There doesn’t seem to be any difference in the two methods

File.directory? can test if a named file is a dir

December 10, 2012
0 thanks


Including module in a class does not automatically over-write methods defined with the same name.


module Mod

def exit(code = 0)
  puts "Exiting with code #{code}"


class OriginalClass

include Mod
def exit
  puts "Original message"


OriginalClass.new.exit 99


exit': wrong number of arguments (1 for 0) (ArgumentError)

if you use this construct, the alias_method will work similar to super:

module Mod

alias_method :super_exit, :exit
def self.included base
  base.instance_eval do
    def exit(code = 0)
      puts "Exiting with code #{code}"


December 7, 2012
0 thanks

Beware: default system crypt functionality silently ignores characters beyond the 8th

On some systems:

"1".crypt('aa')                     => "aacFCuAIHhrCM"
"12".crypt('aa')                    => "aa8dJzr7DFMPA"
"123".crypt('aa')                   => "aamrgyQfDFSHw"
"1234".crypt('aa')                  => "aatxRPdZ/m52."
"12345".crypt('aa')                 => "aajt.4s3e3SZA"
"123456".crypt('aa')                => "aaAN1ZUwjW7to"
"1234567".crypt('aa')               => "aaOK9MRbwVNmQ"
"12345678".crypt('aa')              => "aaNN3X.PL2piw"
"123456789".crypt('aa')             => "aaNN3X.PL2piw"
"1234567890".crypt('aa')            => "aaNN3X.PL2piw"
"1234567890abcdefghij".crypt('aa')  => "aaNN3X.PL2piw"
November 14, 2012
0 thanks

What artemave said.

I’d remove my original note if I could, but I can’t see a way how.

October 17, 2012
1 thank

See also: Rack::Utils.parse_nested_query.

Note that CGI::parse does not attempt to create a multi-level object; that is, it basically ignores hard brackets in key names.

For a method that does deal with these, see Rack::Utils.parse_nested_query.

October 10, 2012 - (>= v1_9_1_378)
0 thanks

Bad Example

@nZifnab it is a bad example because an included module is basically a class.

module Mod
    def exit(code = 0)
        puts "Exiting with code #{code}"

include Mod

exit 99


Exiting with code 99
September 10, 2012
0 thanks

Reports originally defined method names, not invoked names in Ruby 1.9.x

In Ruby 1.8.7, the reported method names were those of the methods actually invoked, so if #b was an alias for #a, and #b was called, it would be reported as “… in `b’”. In Ruby 1.9, the same invocation is now reported as “… in `a’”.

Unfortunately, this change disables the hack that could formerly be used to create a variant of __method__ that returns the method as actually invoked. The new __callee__ method is no help with that, because it is currently synonymous with __method__.

September 10, 2012
0 thanks

__callee__ and __method__ both return symbol when originally defined, not current

There has been some indication that __callee__ is intended to return the symbol with which the method was actually invoked, whereas __method__ returns name with which the method was originally defined, but __callee__ actually behaves identically to __method__ in Ruby 1.9.1 1.9.2, and 1.9.3.

This distinction is meaningful, because methods can be aliased after they are created.

In Ruby 1.8.7, it was possible (though) not convenient to get the name of the method as actually invoked, by calling another method that extracts the name from caller.first. Even that hack no longer works in Ruby 1.9 though, since it will return the originally defined method name as well.

August 6, 2012
0 thanks

What it do?

For those favoring YAML outputs, this methods simply and recursively outputs the keys and values in YAML (into a String) for your pleasure.

July 23, 2012
2 thanks

Long-wanted functional extension

This is pretty nice method allowing you to build stuff in a functional way.

Lets say you want to build a hash from an array, keyed by array object, where each value is the number of same objects in the array.

# imperative style :-P

h = Hash.new(0)
[1, 3, 2, 3, 1, 3].each { |i| h[i] += 1 }
h # => {1=>2, 3=>3, 2=>1} 

# functional style, using inject. Note that you need to explicitly return the accumulator in the end

[1, 3, 2, 3, 1, 3].inject(Hash.new(0)) { |a, i| a[i] += 1; a } 
# => {1=>2, 3=>3, 2=>1} 

# using each_with_object. Note the reversed block params - accumulator is the last parameter. 
# Mnemonic: consistent with each_with_index, where object is the first parameter

[1, 3, 2, 3, 1, 3].each_with_object(Hash.new(0)) {|i, a| a[i] += 1}
# => {1=>2, 3=>3, 2=>1} 
July 19, 2012
0 thanks

Assignment using 'key: value'

Another shorthand way of assigning key, value pairs:

Hash[one: 1, two: 2] #=> {:one=>1, :two=>2}
June 28, 2012
0 thanks

see also – similar methods

See also DateTime#strftime and Date#strftime . (They work similarly, but have different APIdock notes.)

June 28, 2012
0 thanks

see also – similar methods

See also Time#strftime and DateTime#strftime . (They work similarly, but have different APIdock notes.)

June 28, 2012
0 thanks

see also – similar methods

See also Time#strftime and Date#strftime . (They work similarly, but have different APIdock notes.)

June 22, 2012 - (v1_8_6_287 - v1_9_3_125)
3 thanks

Test if an array is included in another


class Array
   def included_in? array

[1,2,4].included_in?([1,10,2,34,4]) #=> true
June 11, 2012
0 thanks

more_than? instance method

Over the weekend I kept running into instances where I was writing code like this:

Code example

arr = ['hello', 'world']

if arr.length > 2
 # do stuff
 # do something else

So I ended up extending the core and adding an instance method of more_than?

Code example

class Array
  def more_than?(num)
    length > num


arr = ['hello', 'world']
puts "Hello" if arr.more_than? 1
May 26, 2012 - (v1_9_3_125)
0 thanks

rindex with identically array elements

Code Example

a = [1,1,1]
a.rindex( a.min ) #=> 2
May 17, 2012
0 thanks

Starts with capital letter alternative

Just adding an anchor to the regular expression seems simpler (and was faster in my benchmarks, not that that matters much):

'Abracadabra' =~ /^[A-Z]/
May 15, 2012
0 thanks



May 13, 2012
2 thanks

Undefined Method `mktmpdir' for Dir:Class

Be sure to

require 'tmpdir'

before using it. Read more at http://mikbe.tk/2011/03/07/temporary-directory.

May 3, 2012
0 thanks

Starts with a Capital Letter

(or any regular expression you’d like)

'Abracadabra'[0..0] =~ /[A-Z]/       # => true
April 26, 2012 - (v1_9_3_125)
0 thanks


The documentation is using File.directory?(“/path/to/directory”), but the method being referred to is Dir.exists?().

 => true

The source code is the same as File.directory?().

April 24, 2012 - (v1_9_3_125)
0 thanks


Instantiates a new blank object (devoid of methods). The only class method of class BasicObject. see “ri BasicObject”


> o=BasicObject.new (Object doesn’t support #inspect)


> o.methods NoMethodError: undefined method `methods’ for #<BasicObject:0x0000000267a0a0>

> def o.to_s > self > end

> nil

> o

> #<BasicObject:0x0000000267a0a0>

April 9, 2012
This note might be spam Show
March 18, 2012
0 thanks

Use Join to Turn Array Items into a String.

If you’re looking to take an array like

[ 'don', 'draper' ]

And get

'don draper'

Then use join instead:

[ 'don', 'draper' ].join( ' ' ) 

#=> 'don draper'
March 18, 2012
0 thanks

Destructive to the Original String.

Just as an FYI this function is destructive to the original String object.

name = 'draper' #=> "draper"

name.insert( 0, 'don ' ) #=> 'don draper'

name #=> 'don draper'