Why doesn't >> prepend strings in Ruby? - ruby

In ruby, you can append strings using <<:
>> "Hello" << "World"
=> "HelloWorld"
So why can't you prepend them using >>?
>> "Hello" >> "World"
NoMethodError: undefined method `>>' for "Hello":String
I realise String doesn't have the >> method defined, but what's the reasoning behind that?

Ruby 1.9.3 added a String#prepend method.
The proposal about adding prepend[1] also included the ">>" method, and there's some discussion on the thread about that implementation [2]:
Matz says: " >> is interesting notation did not think about it."
sorya says: "This patch is out it had been discussed several times towards the IRC"
However at the end of the thread, the conclusion was to accept String#prepend, and that "other proposals including String # >> are pending."
I couldn't find any other discussion about it though... anyone else?
Personally, I like it, and it's trivial to add:
class String
def >> (s)
s.prepend(self)
end
end
The result:
>> "Hello" >> "World"
=> "HelloWorld"
[1] http://bugs.ruby-lang.org/issues/3675
[2] http://translate.google.com/translate?hl=en&sl=ja&tl=en&u=http%3A%2F%2Fbugs.ruby-lang.org%2Fissues%2F3675

Ruby's syntax wouldn't allow a method like >> to be implemented the way you expect.
<< in "Hello" << "World" is equivalent to the following:
"Hello".<<("World")
If you wanted to create a prepend method >>, I would expect "Hello" in "Hello" >> "World" to be the argument to the string "World":
("Hello")>>."World" which isn't valid Ruby syntax.
If "World" was an argument to "Hello", then you would just be appending a string like fl00r demonstrated. Aliasing >> to mean the same as << would cause confusion.
This is why you have the insert method instead. If you want to insert "Hello" in front of "World" you would call insert on "World":
"World".insert(0, "Hello ")
The takeaway here is to keep in mind that << is a method call just like a string method such as length, so you have to keep the ordering similar to regular method calls.

Ruby always asigns value from the right to the left.
But you can implement it by yourself
class String
def >>(s)
s << self
end
end
"Hello" >> "world"
#=> "worldHello"

I don't think I would do this, but if someone forced me to:
class String
def prepend(string)
insert(0, string)
end
end
I don't think >> is a good idea—the reason << is nice is because it looks like what's going to happen. >> looks like it would have the same result as << to me, except that the calling object is being prepended onto the parameter.

I think this is a good question, and the issue is more general than just the problem with the notation << as suggested in McStretch's answer because there is a same situation with the methods given in an alphabet. Namely, there is String#concat, which appends an argument string to self, but there is no method that prepends an argument string.

Related

Why does double shovel in Ruby not mutate state?

I ran into this weird side effect that caused a bug or confusion. So imagine that this isn't a trivial example but an example of a gotcha perhaps.
name = "Zorg"
def say_hello(name)
greeting = "Hi there, " << name << "?"
puts greeting
end
say_hello(name)
puts name
# Hi there, Zorg?
# Zorg
This doesn't mutate name. Name is still Zorg.
But now look at a very subtle difference. in this next example:
name = "Zorg"
def say_hello(name)
greeting = name << "?"
puts "Hi there, #{greeting}"
end
say_hello(name)
puts name
# Hi there, Zorg?
# Zorg? <-- name has mutated
Now name is Zorg?. Crazy. Very subtle difference in the greeting = assignment. Ruby is doing something internally with the parsing (?) or message passing chaining? I thought this would just chain the shovels like name.<<("?") along but I guess this isn't happening.
This is why I avoid the shovel operator when trying to do concatenation. I generally try to avoid mutating state when I can but Ruby (currently) isn't optimized for this (yet). Maybe Ruby 3 will change things. Sorry for scope-creep / side discussion about the future of Ruby.
I think this is particularly weird since the example with less side effects (first one) has two shovel operators where the example with more side effects has fewer shovel operators.
Update
You are correct DigitalRoss, I'm making it too complicated.
Reduced example:
one = "1"
two = "2"
three = "3"
message = one << two << three
Now what do you think everything is set to? (no peeking!)
If I had to guess I'd say:
one is 123
two is 23
three is 3
message is 123
But I'd be wrong about two. Two is 2.
If we convert your a << b << c construct to a more method-ish form and throw in a bunch of implicit parentheses the behavior should be clearer. Rewriting:
greeting = "Hi there, " << name << "?"
yields:
greeting = ("Hi there, ".<<(name)).<<("?")
String#<< is modifying things but name never appears as the target/LHS of <<, the "Hi there ," << name string does but name doesn't. If you replace the first string literal with a variable:
hi_there = 'Hi there, '
greeting = hi_there << name << '?'
puts hi_there
you'll see that << changed hi_there; in your "Hi there, " case, this change was hidden because you were modifying something (a string literal) that you couldn't look at afterwards.
You are making it too complicated.
The operator returns the left-hand side and so in the first case it's just reading name (because "Hi there, " << name is evaluated first) but in the second example it is writing it.
Now, many Ruby operators are right-associative, but << is not one of them. See: https://stackoverflow.com/a/21060235/140740
The right-hand side of your = is evaluated left to right.
When you are doing
"Hello" << name << "?"
The operation starts with "Hello", adds name to it, then adds "?" to the mutated "Hello".
When you do
name << "?"
The operation starts with name, and adds "?" to it, mutating name (which exists outside the internal scope of the method.
So in your example of one << two << three, you are mutating only one.

Getting the last line printed in Ruby

Is there any way to get the output of the last string sent to output? For instance:
puts "Hello"
puts _+" World"
Would return
Hello
Hello World
The assignment I'm working on involves minimizing code as much as possible. The above example is not the assignment, but if such a variable exists it would certainly help.
Thanks
** EDIT **
#gnibbler has the closest answer to what I'm looking for. This has nothing to do with spacing. I need to reuse the data output on the previous line, not append to it. Another example would be:
puts "foobar" // foobar
puts _.reverse // raboof
Yeah its possible. You need to override the Kernel::puts method likes this
module Kernel
alias_method :old_puts, :puts
def puts arg
old_puts arg
$_=arg # $_ is a global variable, holds the last printed item
end
end
and use it like
>> puts "sample"
=> "sample"
>> _
=> "sample"
>> _.reverse
=> "elpmas"
_ will always holds the last printed value
it means
>> puts "hello"
=> "hello"
>> puts _ + " word"
=> "hello word"
>> _
=> "hello word"
Is there a reason that you want to do this?maybe there is other solutions. If you really wants to do, you can do like this:
module Kernel
alias_method :puts_with_save, :puts
def puts_with_save arg_
puts arg_
$LastPuts = arg_
end
end
puts_with_save "hello"
puts_with_save $LastPuts + " shanison"
This should work as you expected. But I introduce a global $LastPuts to your program.
There is no special variable for that
apart from patching puts (which will conflict with your requirement to minimise the code), you could use a pattern like this
puts w="Hello"
puts w=(w+" World")
puts w=(w.reverse)
etc.
The only thing I can think of is that if you knew you were using puts you could patch it with your own version to give it a "memory" to suit your objective. However, it sounds like in your case you may as well use a separate mechanism rather than overriding the default behavior of puts.

Why can I not concatenate two strings and assign them to a symbol?

. . . as in this example:
helloworld.rb:1: syntax error, unexpected '=', expecting $end
:helloworld = "hello ".concat("world")
I thought if I use concat I'm modifying the string "hello " and adding "world" to it and then ultimately assigning the resulting string - "hello world" - to the :helloworld symbol on the left side of the equals sign. I thought that would be legal, just as if I had written:
:helloworld = "hello world"
oh, wait, that doesn't work either. (scratches head).
Ruby symbols cannot have values assigned to them since they represent a canonical value. If you want to build a symbol from a string, you can use "hello ".concat("world").to_sym.
Try this:
:"hello world"
symbols are confusing when coming from languages that don't have anything like them. You can't assign to symbols, that's not what they're for.
Here are a couple of examples that may help explain it.
5.times do |i|
# a new string is created in each iteration of the loop
puts "my string".object_id
# there is only ever one symbol for each possible value
# so a new object is not created during each iteration
puts :my_symbol.object_id
# this often makes a difference when you're using them for things like hash keys
#some_method(:name => 'bob')
#some_method('name' => 'bob')
end
The other big difference is that a symbol comparison is simply a pointer comparison.
Perhaps what you're actually looking for is a constant? They can be dynamically generated, referred to later, and you get a warning if you try to reassign one.
>> HELLO_WORLD = "hello ".concat("world")
=> "hello world"
>> HELLO_WORLD = "foo"
(irb):3: warning: already initialized constant HELLO_WORLD
=> "foo"
You cannot assign to a symbol but you can return a symbol which is a concatenation of other symbols, although you have to pass through strings as far as I know (I'd like to know if there is a better way).
Suppose you want to obtain the symbol :myway starting from the symbols :my and :way ;
(:my.to_s + :way.to_s).to_sym # return :myway
Well, yeah. You can't assign to symbols. Do you mean something like:
foo = { :helloworld => "hello ".concat("world") }
?
class Symbol
def + (to)
return "#{self}#{to}".to_sym
end
end
This worked for me
#foo = 'world'
"hello #{#foo}".to_s.to_sym
output=> :"hello world"
You can make a function using default ruby string to symbol conversion.
Follow the example
def sum_of_two_sym(sym1, sym2)
(sym1.to_s + sym2.to_s).to_sym
end
sum_of_two_sym(:hello, :world)
Result will show :helloworld
Here I just write a function, the name of function sum_of_two_sym I pass two parameter :hello and :world in two argument sym1 and sym2 then sym1 and sym2 convert to string and concatenate them and finally result convert string to symbol and return.

Why don't numbers support .dup?

>> a = 5
=> 5
>> b = "hello, world!"
=> "hello, world!"
>> b.dup
=> "hello, world!"
>> a.dup
TypeError: can't dup Fixnum
from (irb):4:in `dup'
from (irb):4
I understand that Ruby will make a copy every time you assign an integer to a new variable, but why does Numeric#dup raise an error?
Wouldn't this break abstraction, since all objects should be expected to respond to .dup properly?
Rewriting the dup method will fix the problem, as far as I can tell:
>> class Numeric
>> def dup()
>> self
>> end
>> end
Does this have a downside I'm not seeing? Why isn't this built into Ruby?
Most objects in Ruby are passed by reference and can be dupped. Eg:
s = "Hello"
t = s # s & t reference to the same string
t.upcase! # modifying either one will affect the other
s # ==> "HELLO"
A few objects in Ruby are immediate, though. They are passed by value, there can only be one of this value and it therefore cannot be duped. These are any (small) integers, true, false, symbols and nil. Many floats are also immediates in Ruby 2.0 on 64 bit systems.
In this (preposterous) example, any "42" will hold the same instance variable.
class Fixnum
attr_accessor :name
alias_method :original_to_s, :to_s
def to_s
name || original_to_s
end
end
42.name = "The Answer"
puts *41..43 # => 41, The Answer, 43
Since you would normally expect something.dup.name = "new name" to not affect any other object than the copy obtained with dup, Ruby chooses not to define dup on immediates.
Your question is more complex than it appears. There was some discussion on ruby-core as to how this can be made easier. Also, other types of Numeric objects (floats, bignums, rationals and complex numbers) can not be duped although they are not immediates either.
Note that ActiveSupport (part of rails) provide the method duplicable? on all objects
The problem with the dup() function that you defined is that it doesn't return a copy of the object, but rather returns the object itself. This is not what a duplicate procedure is supposed to do.
I don't know Ruby, but a possible reason I can think of for dup not being defined for numbers is that a number is a basic type and thus, doing something like:
>> a = 5
>> b = a
would automatically assign the value 5 into the variable b, as opposed to making b and a point to the same value in memory.

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