Using a different result for each instance of insertion in gsub - ruby

Say my program such was thus:
my_string = "I think we should implement <random_plan> instead of <random_plan>"
def generate_random_plan
#Some code that returns a string that is not the same every time the method is called, involving randomness.
end
puts my_string.gsub("<random_plan>", generate_random_plan)
So as I have written it, it would print something like "I think we should implement plan H instead of plan H". When what I really want is for gsub to call the method each time it performs a substitution, so I can end up with "I think we should implement plan D instead of plan Q". I have a sneaking suspicious the gsub method just isn't built for that and it can't be done, so could you suggest the easiest way to make this happen?

One basic principle in Ruby is "when in doubt, try a code block." In fact, gsub() accepts a code block in place of a string for its second parameter.
Here's an example that is something like what you're looking for:
'axbxcxdxe'.gsub( 'x' ) { rand(9) }
Try that code in irb and you'll get random digits for the x's:
a0b6c0d3e
The replacement code block is a powerful feature, especially because it receives the original matched string as a parameter. As a contrived example, suppose you wanted to convert only the vowels in a string to uppercase:
def vowelup( s )
s.gsub( /[aeiouy]/ ) { |c| c.upcase }
end
print vowelup( 'Stack Overflow' )
This prints:
StAck OvErflOw
JavaScript has essentially the same feature too:
function vowelup( s ) {
return s.replace( /[aeiouy]/g, function( c ) {
return c.toUpperCase();
});
}
console.log( vowelup('Stack Overflow') );

gsub accepts a block and, if given, calls it on each match. Return your random value from it.
my_string = "I think we should implement <random_plan> instead of <random_plan>"
def generate_random_plan s
plans = ('A'..'Z').to_a
s.gsub('<random_plan>') do
plans.sample # random plan
end
end
generate_random_plan my_string # => "I think we should implement A instead of J"
generate_random_plan my_string # => "I think we should implement Q instead of A"
generate_random_plan my_string # => "I think we should implement Z instead of H"

Related

Load function from variable name (Ruby)

Here's a short example of my problem.
prefix = "!"
commands = ["right"]
response = nil
message = "Some text !right here"
for i in 0..commands.length
if message.include?(prefix + commands[i]) # If message contains "!right"
response = commands[i](parameter) # Load matching function
end
end
if response
puts(response)
end
def right(parameter)
"This is an example response"
end
Why can't I load the function right by doing it like this?
First of all, numeric for loops are usually not used in ruby. You can just write
commands.each do |command|
...
end
As for calling "functions", you need to know that functions as such don't exist in ruby, only methods (which are, in theory, just a special case of function).
To call a method on an object, you use the send method, which "sends" (read: calls) a "message" (read: the method name) to the object.
The send method takes a symbol as its argument, which is in practice just an interned string, but you're supposed to use them differently from normal strings.
Last but not least, how can you write def outside of any class to define a function, but it's still somehow a method? That's because Ruby pretty much wraps your entire code in an implicit object.
In practice, you'll be better off using a lambda, which is really just an object with a call method that simulates first class functions as you may know them from javascript, lua, etc.
The syntactic sugar for defining one is whatever = lambda { |argument| puts "I'm a lambda" } or whatever = ->(argument){ puts "I'm a lambda too" }.
do |argumetn| ... some lines of code ... end syntax can also be used with both lambda and -> notations.
You can then call the lambda with whatever.call(<argument>)
There's also Procs, which are like lambdas, but with a few differences and I suggest you just google it if you want to know what exactly they are.
Assuming each command is a lambda (or a proc), to assign each one to a string, I recommend just using a hash (read: map or dict).
They are defined like this:
my_map_variable = {
20 => "I'm an integer",
"string" => "I'm a string",
:symbol => "I'm a symbol, an interned string",
symbol2: "I'm the same as above, but with fancy notation",
right: -> (parameter) { puts "This is an example response" }
}
You can then access the values like this
puts my_map_variable[20] # prints: I'm an integer
puts my_map_variable[:symbol2]
puts my_map_variable[:right].call(nil) # prints: "This is an example response"
Lastly, if you have a string "right", but your hash uses symbol indices, you can just call "right".to_sym to turn the string into a symbol. Or you can just use strings in the first place.

Is there a way to pass a regex capture to a block in Ruby?

I have a hash with a regex for the key and a block for the value. Something like the following:
{ 'test (.+?)' => { puts $1 } }
Not exactly like that, obviously, since the block is being stored as a Proc, but that's the idea.
I then have a regex match later on that looks a lot like this
hash.each do |pattern, action|
if /#{pattern}/i.match(string)
action.call
end
end
The idea was to store the block away in the hash to make it a bit easier for me to expand upon in the future, but now the regex capture doesn't get passed to the block. Is there a way to do this cleanly that would support any number of captures I put in the regex (as in, some regex patterns may have 1 capture, others may have 3)?
What if you pass the match data into your procs?
hash.each do |pattern, action|
if pattern.match(string)
action.call($~)
end
end
Your hash would become:
{ /test (.+?)/i => lambda { |matchdata| puts matchdata[1] } }
I would use Hash.find which walks the hash elements, passing them into a block, one at a time. The one that returns true wins:
Something like this:
hash = {/foo/ => lambda { 'foo' }, /bar/ => lambda { 'bar' } }
str = 'foo'
puts hash.find{ |n,v| str =~ n }.to_a.last.call
Obviously I'm using lambda but it's close enough. And, if there was no match you need to handle nil values. For the example I chained to_a.last.call but in real life you'd want to react to a nil otherwise Ruby will get mad.
If you are searching through a lot of patterns, or processing a lot of text, your search will be slowed down by having to recompile the regex each time. I'd recommend storing the keys as regex objects to avoid that.

Elegant way of duck-typing strings, symbols and arrays?

This is for an already existing public API that I cannot break, but I do wish to extend.
Currently the method takes a string or a symbol or anything else that makes sense when passed as the first parameter to send
I'd like to add the ability to send a list of strings, symbols, et cetera. I could just use is_a? Array, but there are other ways of sending lists, and that's not very ruby-ish.
I'll be calling map on the list, so the first inclination is to use respond_to? :map. But a string also responds to :map, so that won't work.
How about treating them all as Arrays? The behavior you want for Strings is the same as for an Array containing only that String:
def foo(obj, arg)
[*arg].each { |method| obj.send(method) }
end
The [*arg] trick works because the splat operator (*) turns a single element into itself or an Array into an inline list of its elements.
Later
This is basically just a syntactically sweetened version or Arnaud's answer, though there are subtle differences if you pass an Array containing other Arrays.
Later still
There's an additional difference having to do with foo's return value. If you call foo(bar, :baz), you might be surprised to get [baz] back. To solve this, you can add a Kestrel:
def foo(obj, arg)
returning(arg) do |args|
[*args].each { |method| obj.send(method) }
end
end
which will always return arg as passed. Or you could do returning(obj) so you could chain calls to foo. It's up to you what sort of return-value behavior you want.
A critical detail that was overlooked in all of the answers: strings do not respond to :map, so the simplest answer is in the original question: just use respond_to? :map.
Since Array and String are both Enumerables, there's not an elegant way to say "a thing that's an Enumberable, but not a String," at least not in the way being discussed.
What I would do is duck-type for Enumerable (responds_to? :[]) and then use a case statement, like so:
def foo(obj, arg)
if arg.respond_to?(:[])
case arg
when String then obj.send(arg)
else arg.each { |method_name| obj.send(method_name) }
end
end
end
or even cleaner:
def foo(obj, arg)
case arg
when String then obj.send(arg)
when Enumerable then arg.each { |method| obj.send(method) }
else nil
end
end
Perhaps the question wasn't clear enough, but a night's sleep showed me two clean ways to answer this question.
1: to_sym is available on String and Symbol and should be available on anything that quacks like a string.
if arg.respond_to? :to_sym
obj.send(arg, ...)
else
# do array stuff
end
2: send throws TypeError when passed an array.
begin
obj.send(arg, ...)
rescue TypeError
# do array stuff
end
I particularly like #2. I severely doubt any of the users of the old API are expecting TypeError to be raised by this method...
Let's say your function is named func
I would make an array from the parameters with
def func(param)
a = Array.new
a << param
a.flatten!
func_array(a)
end
You end up with implementing your function func_array for arrays only
with func("hello world") you'll get a.flatten! => [ "hello world" ]
with func(["hello", "world"] ) you'll get a.flatten! => [ "hello", "world" ]
Can you just switch behavior based on parameter.class.name? It's ugly, but if I understand correctly, you have a single method that you'll be passing multiple types to - you'll have to differentiate somehow.
Alternatively, just add a method that handles an array type parameter. It's slightly different behavior so an extra method might make sense.
Use Marshal to serialize your objects before sending these.
If you don't want to monkeypatch, just massage the list to an appropriate string before the send. If you don't mind monkeypatching or inheriting, but want to keep the same method signature:
class ToBePatched
alias_method :__old_takes_a_string, :takes_a_string
#since the old method wanted only a string, check for a string and call the old method
# otherwise do your business with the map on things that respond to a map.
def takes_a_string( string_or_mappable )
return __old_takes_a_string( string_or_mappable ) if String === string_or_mappable
raise ArgumentError unless string_or_mappable.responds_to?( :map )
# do whatever you wish to do
end
end
Between those 3 types I'd do this
is_array = var.respond_to?(:to_h)
is_string = var.respond_to?(:each_char)
is_symbol = var.respond_to?(:to_proc)
Should give a unique answer for [], :sym, 'str'

can you define a block inline with ruby?

Is it possible to define a block in an inline statement with ruby? Something like this:
tasks.collect(&:title).to_block{|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}" }
Instead of this:
titles = tasks.collect(&:title)
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"
If you said tasks.collect(&:title).slice(0, this.length-1) how can you make 'this' refer to the full array that was passed to slice()?
Basically I'm just looking for a way to pass the object returned from one statement into another one, not necessarily iterating over it.
You're kind of confusing passing a return value to a method/function and calling a method on the returned value. The way to do what you described is this:
lambda {|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}"}.call(tasks.collect(&:title))
If you want to do it the way you were attempting, the closest match is instance_eval, which lets you run a block within the context of an object. So that would be:
tasks.collect(&:title).instance_eval {"#{slice(0, length - 1).join(", ")} and #{last}"}
However, I would not do either of those, as it's longer and less readable than the alternative.
I'm not sure exactly what you're trying to do, but:
If you said tasks.collect(&:title).slice(0, this.length-1) how can you make 'this' refer to the full array that was passed to slice()?
Use a negative number:
tasks.collect(&:title)[0..-2]
Also, in:
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"
you've got something weird going on with your quotes, I think.
I don't really understand why you would want to, but you could add a function to the ruby classes that takes a block, and passes itself as a parameter...
class Object
def to_block
yield self
end
end
At this point you would be able to call:
tasks.collect(&:title).to_block{|it| it.slice(0, it.length-1)}
Of course, modifying the Object class should not be taken lightly as there can be serious consequences when combining with other libraries.
Although there are many good answers here, perhaps you're looking for something more like this in terms of an objective:
class Array
def andjoin(separator = ', ', word = ' and ')
case (length)
when 0
''
when 1
last.to_s
when 2
join(word)
else
slice(0, length - 1).join(separator) + word + last.to_s
end
end
end
puts %w[ think feel enjoy ].andjoin # => "think, feel and enjoy"
puts %w[ mitchell webb ].andjoin # => "mitchell and webb"
puts %w[ yes ].andjoin # => "yes"
puts %w[ happy fun monkeypatch ].andjoin(', ', ', and ') # => "happy, fun, and monkeypatch"

Hidden features of Ruby

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.
Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.
See also:
Hidden features of C#
Hidden features of Java
Hidden features of JavaScript
Hidden features of Ruby on Rails
Hidden features of Python
(Please, just one hidden feature per answer.)
Thank you
From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:
def multiple_of(factor)
Proc.new{|product| product.modulo(factor).zero?}
end
case number
when multiple_of(3)
puts "Multiple of 3"
when multiple_of(7)
puts "Multiple of 7"
end
Peter Cooper has a good list 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:
[*items].each do |item|
# ...
end
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:
fruit = ["apple","red","banana","yellow"]
=> ["apple", "red", "banana", "yellow"]
Hash[*fruit]
=> {"apple"=>"red", "banana"=>"yellow"}
One trick I like is to use the splat (*) expander on objects other than Arrays. Here's an example on a regular expression match:
match, text, number = *"Something 981".match(/([A-z]*) ([0-9]*)/)
Other examples include:
a, b, c = *('A'..'Z')
Job = Struct.new(:name, :occupation)
tom = Job.new("Tom", "Developer")
name, occupation = *tom
Wow, no one mentioned the flip flop operator:
1.upto(100) do |i|
puts i if (i == 3)..(i == 15)
end
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.
For instance, to create a class that has an unknown superclass until run time, i.e. is random, you could do the following:
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample
end
RandomSubclass.superclass # could output one of 6 different classes.
This uses the 1.9 Array#sample method (in 1.8.7-only, see Array#choice), and the example is pretty contrived but you can see the power here.
Another cool example is the ability to put default parameter values that are non fixed (like other languages often demand):
def do_something_at(something, at = Time.now)
# ...
end
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.
However, in the second example, each time you call do_something_at, the at variable will be the time that the method was called (well, very very close to it)
Another tiny feature - convert a Fixnum into any base up to 36:
>> 1234567890.to_s(2)
=> "1001001100101100000001011010010"
>> 1234567890.to_s(8)
=> "11145401322"
>> 1234567890.to_s(16)
=> "499602d2"
>> 1234567890.to_s(24)
=> "6b1230i"
>> 1234567890.to_s(36)
=> "kf12oi"
And as Huw Walters has commented, converting the other way is just as simple:
>> "kf12oi".to_i(36)
=> 1234567890
Hashes with default values! An array in this case.
parties = Hash.new {|hash, key| hash[key] = [] }
parties["Summer party"]
# => []
parties["Summer party"] << "Joe"
parties["Other party"] << "Jane"
Very useful in metaprogramming.
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:
it_is_day_of_week = lambda{ |day_of_week, date| date.wday == day_of_week }
it_is_saturday = it_is_day_of_week.curry[6]
it_is_sunday = it_is_day_of_week.curry[0]
case Time.now
when it_is_saturday
puts "Saturday!"
when it_is_sunday
puts "Sunday!"
else
puts "Not the weekend"
end
Download Ruby 1.9 source, and issue make golf, then you can do things like this:
make golf
./goruby -e 'h'
# => Hello, world!
./goruby -e 'p St'
# => StandardError
./goruby -e 'p 1.tf'
# => 1.0
./goruby19 -e 'p Fil.exp(".")'
"/home/manveru/pkgbuilds/ruby-svn/src/trunk"
Read the golf_prelude.c for more neat things hiding away.
Boolean operators on non boolean values.
&& and ||
Both return the value of the last expression evaluated.
Which is why the ||= 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.
However the &&= isn't quite so widely known about.
string &&= string + "suffix"
is equivalent to
if string
string = string + "suffix"
end
It's very handy for destructive operations that should not proceed if the variable is undefined.
The Symbol#to_proc function that Rails provides is really cool.
Instead of
Employee.collect { |emp| emp.name }
You can write:
Employee.collect(&:name)
One final one - in ruby you can use any character you want to delimit strings. Take the following code:
message = "My message"
contrived_example = "<div id=\"contrived\">#{message}</div>"
If you don't want to escape the double-quotes within the string, you can simply use a different delimiter:
contrived_example = %{<div id="contrived-example">#{message}</div>}
contrived_example = %[<div id="contrived-example">#{message}</div>]
As well as avoiding having to escape delimiters, you can use these delimiters for nicer multiline strings:
sql = %{
SELECT strings
FROM complicated_table
WHERE complicated_condition = '1'
}
Use a Range object as an infinite lazy list:
Inf = 1.0 / 0
(1..Inf).take(5) #=> [1, 2, 3, 4, 5]
More info here: http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/
I find using the define_method command to dynamically generate methods to be quite interesting and not as well known. For example:
((0..9).each do |n|
define_method "press_#{n}" do
#number = #number.to_i * 10 + n
end
end
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.
module_function
Module methods that are declared as module_function will create copies of themselves as private instance methods in the class that includes the Module:
module M
def not!
'not!'
end
module_function :not!
end
class C
include M
def fun
not!
end
end
M.not! # => 'not!
C.new.fun # => 'not!'
C.new.not! # => NoMethodError: private method `not!' called for #<C:0x1261a00>
If you use module_function without any arguments, then any module methods that comes after the module_function statement will automatically become module_functions themselves.
module M
module_function
def not!
'not!'
end
def yea!
'yea!'
end
end
class C
include M
def fun
not! + ' ' + yea!
end
end
M.not! # => 'not!'
M.yea! # => 'yea!'
C.new.fun # => 'not! yea!'
Short inject, like such:
Sum of range:
(1..10).inject(:+)
=> 55
Warning: this item was voted #1 Most Horrendous Hack of 2008, so use with care. Actually, avoid it like the plague, but it is most certainly Hidden Ruby.
Superators Add New Operators to Ruby
Ever want a super-secret handshake operator for some unique operation in your code? Like playing code golf? Try operators like
-~+~-
or
<---
That last one is used in the examples for reversing the order of an item.
I have nothing to do with the Superators Project beyond admiring it.
I'm late to the party, but:
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:
a = [:x, :y, :z]
b = [123, 456, 789]
Hash[a.zip(b)]
# => { :x => 123, :y => 456, :z => 789 }
(This works because Array#zip "zips" up the values from the two arrays:
a.zip(b) # => [[:x, 123], [:y, 456], [:z, 789]]
And Hash[] can take just such an array. I've seen people do this as well:
Hash[*a.zip(b).flatten] # unnecessary!
Which yields the same result, but the splat and flatten are wholly unnecessary--perhaps they weren't in the past?)
Auto-vivifying hashes in Ruby
def cnh # silly name "create nested hash"
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # => { 1 => { 2 => { 3 =>4 } } }
This can just be damn handy.
Destructuring an Array
(a, b), c, d = [ [:a, :b ], :c, [:d1, :d2] ]
Where:
a #=> :a
b #=> :b
c #=> :c
d #=> [:d1, :d2]
Using this technique we can use simple assignment to get the exact values we want out of nested array of any depth.
Class.new()
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 const_set/const_get/const_defined? to get your new class properly registered, so that inspect prints out a name instead of a number.
Not something you need every day, but quite handy when you do.
create an array of consecutive numbers:
x = [*0..5]
sets x to [0, 1, 2, 3, 4, 5]
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 attr_accessor, attr_reader, and attr_writer 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 has_one and belongs_to.
But it's pretty simple to create your own metaprogramming tricks using class_eval to execute dynamically-written code.
The following example allows a wrapper object to forwards certain methods along to an internal object:
class Wrapper
attr_accessor :internal
def self.forwards(*methods)
methods.each do |method|
define_method method do |*arguments, &block|
internal.send method, *arguments, &block
end
end
end
forwards :to_i, :length, :split
end
w = Wrapper.new
w.internal = "12 13 14"
w.to_i # => 12
w.length # => 8
w.split('1') # => ["", "2 ", "3 ", "4"]
The method Wrapper.forwards takes symbols for the names of methods and stores them in the methods array. Then, for each of those given, we use define_method to create a new method whose job it is to send the message along, including all arguments and blocks.
A great resource for metaprogramming issues is Why the Lucky Stiff's "Seeing Metaprogramming Clearly".
use anything that responds to ===(obj) for case comparisons:
case foo
when /baz/
do_something_with_the_string_matching_baz
when 12..15
do_something_with_the_integer_between_12_and_15
when lambda { |x| x % 5 == 0 }
# only works in Ruby 1.9 or if you alias Proc#call as Proc#===
do_something_with_the_integer_that_is_a_multiple_of_5
when Bar
do_something_with_the_instance_of_Bar
when some_object
do_something_with_the_thing_that_matches_some_object
end
Module (and thus Class), Regexp, Date, and many other classes define an instance method :===(other), and can all be used.
Thanks to Farrel for the reminder of Proc#call being aliased as Proc#=== in Ruby 1.9.
The "ruby" binary (at least MRI's) supports a lot of the switches that made perl one-liners quite popular.
Significant ones:
-n Sets up an outer loop with just "gets" - which magically works with given filename or STDIN, setting each read line in $_
-p Similar to -n but with an automatic puts at the end of each loop iteration
-a Automatic call to .split on each input line, stored in $F
-i In-place edit input files
-l Automatic call to .chomp on input
-e Execute a piece of code
-c Check source code
-w With warnings
Some examples:
# Print each line with its number:
ruby -ne 'print($., ": ", $_)' < /etc/irbrc
# Print each line reversed:
ruby -lne 'puts $_.reverse' < /etc/irbrc
# Print the second column from an input CSV (dumb - no balanced quote support etc):
ruby -F, -ane 'puts $F[1]' < /etc/irbrc
# Print lines that contain "eat"
ruby -ne 'puts $_ if /eat/i' < /etc/irbrc
# Same as above:
ruby -pe 'next unless /eat/i' < /etc/irbrc
# Pass-through (like cat, but with possible line-end munging):
ruby -p -e '' < /etc/irbrc
# Uppercase all input:
ruby -p -e '$_.upcase!' < /etc/irbrc
# 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:
ruby -i.bak -p -e '$_.upcase!' /etc/irbrc
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.
The send() 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.
%w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|
button btn, :width => 46, :height => 46 do
method = case btn
when /[0-9]/: 'press_'+btn
when 'Clr': 'press_clear'
when '=': 'press_equals'
when '+': 'press_add'
when '-': 'press_sub'
when '*': 'press_times'
when '/': 'press_div'
end
number.send(method)
number_field.replace strong(number)
end
end
I talk more about this feature in Blogging Shoes: The Simple-Calc Application
Fool some class or module telling it has required something that it really hasn't required:
$" << "something"
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):
For example, Backgroundrb's bdrb_test_helper requires 'test/spec', but you don't use it at all, so in your code:
$" << "test/spec"
require File.join(File.dirname(__FILE__) + "/../bdrb_test_helper")
Defining a method that accepts any number of parameters and just discards them all
def hello(*)
super
puts "hello!"
end
The above hello method only needs to puts "hello" on the screen and call super - but since the superclass hello 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.
private unless Rails.env == 'test'
# e.g. a bundle of methods you want to test directly
Looks like a cool and (in some cases) nice/useful hack/feature of Ruby.

Resources