Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

« Newer Snippets
Older Snippets »
13 total  XML / RSS feed 

writing destructive string methods in Ruby

Use string class' method "replace" to overwrite its "self" value.

Example:

  def decapitalize!
    replace (self.reverse.chop + self.reverse.last.downcase).reverse
  end
  
  def decapitalize
    dup.decapitalize!
  end

Enumerable vs. Enumerator. Standard Library vs. Core Library in Ruby.

Rdoc is causing some serious confusion with libraries.

In core documentation, Enumerable defines each_slice method.

Extend this module into your class and each_slice is not defined.

Reason? each_slice is NOT in the core Enumerable module, but rather the Standard Library Enumerable::Enumerator class, even though the ruby-doc core class documents say otherwise.

You must

require 'enumerator'


to have each_slice is available as a method to your classes.

Benchmark methods

Here we define two ways to process chunks of Array elements at a time.

Below we define a benchmarking test using a double run, one as a preliminary run, one as a real test run.

class Array
  def process(method_obj, batch_size = 10, fin = [])
    if (this_batch = self.first(batch_size)).size > 0
      fin.concat method_obj.call(this_batch)
      (self - this_batch).process(method_obj, batch_size, fin)
    else
      return fin
    end
  end
  
  def proc_array(method_obj, batch_size = 2)
    result = []
    self.each_slice(batch_size) do |batch|
      result.concat method_obj.call(batch)
    end
    result
  end
end

def munge(ary)
  ary.collect { |e| e.+ 10 }
end

my_meth = method(:munge)

BIGARY = Array.new(100) {|i| i}

require 'benchmark'
include Benchmark

bmbm(2) do |test|
  test.report("recursive") do
    10000.times {BIGARY.process(my_meth, 2)}
  end
  test.report("block") do
    10000.times {BIGARY.proc_array(my_meth)}
  end
end

reload modules and files in irb

To reload a changed module, class, etc. file in ruby irb:

load 'filename.rb'


The extension is required in this case

running single test case with ruby testunit

Run only a single test case within your testing file

ruby my_testing_file.rb --name test_casename

irb ruby test case testing

When building test cases for testing ruby classes and modules you can use irb to test your test cases.

require the test/unit files
then include the Test::Unit::Assertions module

load irb from the terminal
require 'test/unit'
include Test::Unit::Assertions


At this point you can use all assertions available through the Assertions module.

Read / Write attributes not keeping value

If a writeable attribute is not keeping its assigned value, check that the write method is using
self.<attribute> = val

, not just
<attribute> = val


Ruby is thinking that = is a local assignment operation, not an assignment of a writeable attribute.

include vs. extend in Ruby

There are multiple ways of extending the functionality of a class in Ruby.
One way is to 'include' a module in a ruby class definition.

class Billy
  include Bully
end

This brings all methods defined in module 'Bully' into Billy as instance methods.

Another way is to 'extend' a class definition with a module
class Billy
  extend Bully
end
Billy.fight(others)

This brings in the methods defined in Bully module, but as class methods

Every object in Ruby implements the 'extend' method. This allows you to extend a class' functionality within an instance through using 'extend'. The module methods brought in are available as instance methods (as compared to using 'extend' within a class definition).
a = Billy.new()
a.extend Bully
a.fight(weaklings)

calling super

When working with a subclass, calling super means you're calling the superclass' method OF THE SAME NAME. Thus you never specify anything with 'super', just arguments, if applicable

def child_method(arg1, arg2)
 super(arg1, arg2)
end

random password generation in Ruby

// description of your code here

chars = ("a".."z").to_a + ("1".."9").to_a 
newpass = Array.new(8, '').collect{chars[rand(chars.size)]}.join

alias class methods in Ruby

module ActiveRecord

  class Base

    class << self
      alias old_establish_connection establish_connection
    end

    def self.establish_connection(arg)
      logger.debug("Establishing connection")
      self.old_establish_connection(arg)
    end
  end
end

Another approach might be to use super like this:
module ActiveRecord
  class Base
    def self.establish_connection(arg)
      logger.debug("Establishing connection")
      super arg
    end
  end
end 

debug print Hpricot xml object

// description of your code here

debug(@instance_var.pretty_inspect)

urlencode in Ruby

Use the CGI class to url encode stuff. Have to load the CGI class before using its methods though.

require 'cgi'
CGI.escape([your junk])
« Newer Snippets
Older Snippets »
13 total  XML / RSS feed