def and undef a method

Jul 25
2008
def my_method; end # define a method
undef my_method    # remove a method

The core manual

Ugly join implementation

Jul 25
2008
arr = (1..10).to_a
 
 str = arr * ', '
 str = arr.join(', ')

Am I going to use the perlish coding style? Not really.

Simple File Manipulation

Jul 21
2008

Ruby file manipulation is as easy as:

MyFile.create "test.txt"
MyFile.add "test.txt", "some content"
MyFile.remove "test.txt"

For example create a file caled fileeasy.rb and add the following module to it:

module FileEasy
 
  def self.included(subject)
    subject.extend(ClassMethods)
  end
 
  module ClassMethods
   alias_method :delete, :remove
   alias_method :unlink, :remove
 
    def create(filename)
      File.open(filename, "w")
    end
    def add(filename, text)
      File.open(filename, "a"){ |f| f < < text }
    end
    def remove(filename)
      File.delete(filename)
    end
  end
 
end

Then test it with irb:

require 'fileeasy'
 
class MyClass
  include FileEasy
end
 
MyFile.create "text.txt"
MyFile.add "text.txt", "test content"
MyFile.remove "text.txt"

Of course this post is just a simple tutorial and the standard library is the best choice – FileUtils.

Simple class’s variable accessor

Jul 19
2008
class Class
  def attr(arg)
    arg = arg.to_s
    if self.class_variables.include?(arg)
      class_eval %(def self.#{arg.sub(/^\@\@/, '')}; #{arg}; end)
    else
      raise ArgumentError, "No such class attribute", caller
    end
  end
end
 
class Test
  @@class_var = "class variable value"
 
  attr :@@class_var
end
 
puts Test.class_var => "class variable value"

Sorting an Array of Hashes with unknown keys

Jul 19
2008
AoH = [{"z"=>26}, {"g"=>7}, {"r"=>18}, {"a"=>1}, {"v"=>22}]
 
# sort by key
AoH.map{|e| e.to_a.flatten}.sort{|x,y| x[0] < => y[0]}
# sort by value
AoH.map{|e| e.to_a.flatten}.sort{|x,y| x[1] < => y[1]}

to truncate or not?

Jul 10
2008
# RoR source code:
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 34
def truncate(text, length = 30, truncate_string = "...")
  if text.nil? then return end
  l = length - truncate_string.chars.length
  text.chars.length > length ? text.chars[0...l] + truncate_string : text
end
 
# My point of view:
def truncate(text, _length = 30, truncate_string = "...")
  text[0..(_length-1)] + truncate_string
end

regexp on String object

Jul 06
2008

Some of the more rarely used string methods:

str = "the tester"
 
str["tester"] #true, the String contains "tester"
str[/\w+\s\w+/] #true, the String matches the regexp

emulates capitalize!

str[/(\w+)/] = ($1[0] - 32).chr

RDoc Documentation

Getting an indication of the number of arguments accepted by a method

Jun 16
2008
class Object
  def arguments?(*methods)
    methods.each do |method|
      begin
        rval = self.method(method).arity
        if rval > 0
          puts "'#{method}' takes fixed (#{rval}) number of argument"
        elsif rval < 0
          puts "'#{method}' takes variable number of arguments"
        elsif rval == 0
          puts "'#{method}' takes no arguments"
        end
      rescue
       puts $!
      end
    end
  end
end
 
String.new.arguments?(:size, :to_i, :scan, :flatten)

www.ruby-doc.org arity

Fun with String class methods

Jun 14
2008
class MyString < String
  # not really useful
  alias + concat
 
  # emulates Array '*' method
  def *(string)
    self.split('').inject('') do |s1,c|
      s1 + c + string
    end
  end
 
  # emulates Array '-' method
  def /(string)
    (self.split('') - string.split('')).to_s
  end
 
  # chars' delimiter
  def delimiter(string)
    self.*(string).sub /.$/, ''
  end
 
end
 
a = MyString.new("abcdef")
b = MyString.new("ABCDEF")
 
puts a * ':'
puts a / (b + "a")
puts a.delimiter(":")
 
#a:b:c:d:e:f:
#bcdef
#a:b:c:d:e:f

Convert an array to a hash

May 04
2008
class Array
  def to_h
    arr = self.dup
    if arr.size % 2 == 0
        Hash[*arr]
    else
        Hash[*arr < < nil]
    end
  end
end

Calendar

February 2012
M T W T F S S
« Sep    
 12345
6789101112
13141516171819
20212223242526
272829  

Tags