Is it possible to access block's scope in method? - ruby

I'd like to write the method (define_variables) which can get a block and use the variables defined in it. Is it possible? For example, I'd like to get 5 in output:
module A
def self.define_variables
yield
puts a # not 5 :(
end
end
A::define_variables do
a = 5
end
Maybe there is some tricks with eval, but haven't found anyone yet.

In short, no. After you've called yield those variables defined in the block are gone (sort of, as we shall see), except for what is returned—that's just how scope works. In your example, the 5 is still there in that it is returned by the block, and thus puts yield would print 5. Using this you could return a hash from the block {:a => 5}, and then access multiple "variables" that way. In Ruby 1.8 (in IRb only) you can do:
eval "a = 5"
a # => 5
Though I don't know of anyway to eval the contents of a block. Regardless, in Ruby 1.9 the scope of eval was isolated and this will give you a NameError. You can do an eval within the context of a Binding though:
def foo
b = yield
eval(a, b) + 2
end
foo do
a = 5
binding
end # => 7
It seems to me that what you're trying to do is emulate macros in Ruby, which is just not possible (at least not pure Ruby), and I discourage the use of any of the "workarounds" I've mentioned above.

Agreed that this is a bit backwards, and Andrew's explanation is correct. If your use case is defining variables, however, there are already class_variable_set and instance_variable_set methods that are great for this:
module A
def self.define_variables(vars = {})
vars.each { |n, v| class_variable_set n, v }
puts ##a
end
end
A::define_variables :##a => 5
The above is more of an example of how it would work within the code you've posted rather than a recommendation.

Related

Plus equals with ruby send message

I'm getting familiar with ruby send method, but for some reason, I can't do something like this
a = 4
a.send(:+=, 1)
For some reason this doesn't work. Then I tried something like
a.send(:=, a.send(:+, 1))
But this doesn't work too. What is the proper way to fire plus equals through 'send'?
I think the basic option is only:
a = a.send(:+, 1)
That is because send is for messages to objects. Assignment modifies a variable, not an object.
It is possible to assign direct to variables with some meta-programming, but the code is convoluted, so far the best I can find is:
a = 1
var_name = :a
eval "#{var_name} = #{var_name}.send(:+, 1)"
puts a # 2
Or using instance variables:
#a = 2
var_name = :#a
instance_variable_set( var_name, instance_variable_get( var_name ).send(:+, 1) )
puts #a # 3
See the below :
p 4.respond_to?(:"+=") # false
p 4.respond_to?(:"=") # false
p 4.respond_to?(:"+") # true
a+=1 is syntactic sugar of a = a+1. But there is no direct method +=. = is an assignment operator,not the method as well. On the other hand Object#send takes method name as its argument. Thus your code will not work,the way you are looking for.
It is because Ruby doesn't have = method. In Ruby = don't work like in C/C++ but it rather assign new object reference to variable, not assign new value to variable.
You can't call a method on a, because a is not an object, it's a variable, and variables aren't objects in Ruby. You are calling a method on 4, but 4 is not the thing you want to modify, a is. It's just not possible.
Note: it is certainly possible to define a method named = or += and call it, but of course those methods will only exist on objects, not variables.
class Fixnum
define_method(:'+=') do |n| self + n end
end
a = 4
a.send(:'+=', 1)
# => 5
a
# => 4
This might miss the mark a bit, but I was trying to do this where a is actually a method dynamically called on an object. For example, with attributes like added_count and updated_count for Importer I wrote the following
class Importer
attr_accessor :added_count, :updated_count
def increment(method)
send("#{method}=", (send(method) + 1))
end
end
So I could use importer.increment(:added_count) or importer.increment(:updated_count)
Now this may seem silly if you only have these 2 different counters but in some cases we have a half dozen or more counters and different conditions on which attr to increment so it can be handy.

Ruby min max assignment operators

When programming ruby I always find myself doing this:
a = [a, b].min
This means compare a and b and store the smallest value in a. I don't like writing the code above as I have to write a twice.
I know that some non-standard dialects of C++ had an operator which did exactly this
a <?= b
Which I find very convenient. But I'm not really interested in the operator as much as I'm in the feature of avoiding repetition. I would also be happy if I could write
a.keep_max(b)
a can be a quite long variable, like my_array[indice1][indice2], and you don't want to write that twice.
I did alot of googling on this and found no result, hopefully this question will pop up and be useful for others aswell.
So, is there any non-repeitive way to express what I want in ruby?
What you would like to do is in fact not possible in ruby (see this question). I think the best you can do is
def max(*args)
args.max
end
a = max a, b
I don't understand your question. You can always do something like this ...
module Comparable
def keep_min(other)
(self <=> other) <= 0 ? self : other
end
def keep_max(other)
(self <=> other) >= 0 ? self : other
end
end
1.keep_min(2)
=> 1
1.keep_max(2)
=> 2
Well, that won't work for all objects with <=> because not all of them are implementing Comparable, so you could monkey-patch Object.
Personally I prefer clarity and tend to avoid monkey-patching. Plus, this clearly is a binary predicate, just like "+", therefore method-chaining doesn't necessarily make sense so I prefer something like this to get rid of that array syntax:
def min(*args)
args.min
end
def max(*args)
args.max
end
min(1, 2)
=> 1
max(1, 2)
=> 2
But hey, I'm also a Python developer :-)
You can define your own method for it:
class Object
def keep_max(other)
[self, other].max
end
end
a = 3
b = 7
puts a.keep_max(b)
But you should be careful defining methods on Object as it can have unpredictable behaviour (for example, if objects cannot be compared).
def keep_max(var, other, binding)
eval "#{var} = [#{var}, #{other}].max", binding
end
a = 5
b = 78
keep_max(:a, :b, binding)
puts a
#=> 78
This basically does what you want. Take a look at Change variable passed in a method

"for" vs "each" in Ruby

I just had a quick question regarding loops in Ruby. Is there a difference between these two ways of iterating through a collection?
# way 1
#collection.each do |item|
# do whatever
end
# way 2
for item in #collection
# do whatever
end
Just wondering if these are exactly the same or if maybe there's a subtle difference (possibly when #collection is nil).
This is the only difference:
each:
irb> [1,2,3].each { |x| }
=> [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
from (irb):2
from :0
for:
irb> for x in [1,2,3]; end
=> [1, 2, 3]
irb> x
=> 3
With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.
Other than that, for is just syntax sugar for the each method.
When #collection is nil both loops throw an exception:
Exception: undefined local variable or method `#collection' for main:Object
See "The Evils of the For Loop" for a good explanation (there's one small difference considering variable scoping).
Using each is considered more idiomatic use of Ruby.
Your first example,
#collection.each do |item|
# do whatever
end
is more idiomatic. While Ruby supports looping constructs like for and while, the block syntax is generally preferred.
Another subtle difference is that any variable you declare within a for loop will be available outside the loop, whereas those within an iterator block are effectively private.
One more different..
number = ["one", "two", "three"]
=> ["one", "two", "three"]
loop1 = []
loop2 = []
number.each do |c|
loop1 << Proc.new { puts c }
end
=> ["one", "two", "three"]
for c in number
loop2 << Proc.new { puts c }
end
=> ["one", "two", "three"]
loop1[1].call
two
=> nil
loop2[1].call
three
=> nil
source: http://paulphilippov.com/articles/enumerable-each-vs-for-loops-in-ruby
for more clear: http://www.ruby-forum.com/topic/179264#784884
Never ever use for it may cause almost untraceable bugs.
Don't be fooled, this is not about idiomatic code or style issues. Ruby's implementation of for has a serious flaw and should not be used.
Here is an example where for introduces a bug,
class Library
def initialize
#ary = []
end
def method_with_block(&block)
#ary << block
end
def method_that_uses_these_blocks
#ary.map(&:call)
end
end
lib = Library.new
for n in %w{foo bar quz}
lib.method_with_block { n }
end
puts lib.method_that_uses_these_blocks
Prints
quz
quz
quz
Using %w{foo bar quz}.each { |n| ... } prints
foo
bar
quz
Why?
In a for loop the variable n is defined once and only and then that one definition is use for all iterations. Hence each blocks refer to the same n which has a value of quz by the time the loop ends. Bug!
In an each loop a fresh variable n is defined for each iteration, for example above the variable n is defined three separate times. Hence each block refer to a separate n with the correct values.
It looks like there is no difference, for uses each underneath.
$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
from (irb):4
Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features.
Per Telemachus's Comment
for .. in .. sets the iterator outside the scope of the loop, so
for a in [1,2]
puts a
end
leaves a defined after the loop is finished. Where as each doesn't. Which is another reason in favor of using each, because the temp variable lives a shorter period.
(1..4).each { |i|
a = 9 if i==3
puts a
}
#nil
#nil
#9
#nil
for i in 1..4
a = 9 if i==3
puts a
end
#nil
#nil
#9
#9
In 'for' loop, local variable is still lives after each loop. In 'each' loop, local variable refreshes after each loop.
As far as I know, using blocks instead of in-language control structures is more idiomatic.
I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.
The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.
This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:
class Apple
TYPES = %w(red green yellow)
def each
yield TYPES.pop until TYPES.empty?
end
end
a = Apple.new
for i in a do
puts i
end
yellow
green
red
=> nil
And now the each iterator:
a = Apple.new
a.each do |i|
puts i
end
yellow
green
red
=> nil
As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).

Named arguments as local variables in Ruby

I find myself constantly writing what I see as unnecessary code in Ruby when using named arguments for methods.
Take for example the following code:
def my_method(args)
orange = args[:orange]
lemon = args[:lemon]
grapefruit = args[:grapefruit]
# code that uses
# orange, lemon & grapefruit in this format which is way prettier & concise than
# args[:orange] args[:lemon] args[:grapefruit]
puts "my_method variables: #{orange}, #{lemon}, #{grapefruit}"
end
my_method :orange => "Orange", :grapefruit => "Grapefruit"
What I really don't like about this code is that I am having to take the args and pass the values into local variables going against DRY principles and just generally taking up space in my methods. And if I don't use local variables and just refer to all variables with the args[:symbol] syntax then the code becomes somewhat illegible.
I have tried working up a solution to this but keeping hitting a brick wall as I don't know how to define local variables using eval in the scope of the method, or using any other technique. Here is one of many attempts below, which results in an error
def my_method_with_eval(args)
method_binding = binding
%w{ orange lemon grapefruit}.each { |variable| eval "#{variable} = args[:#{variable}]", method_binding; }
# code that uses
# orange, lemon & grapefruit in this format which is way prettier & concise than
# args[:orange] args[:lemon] args[:grapefruit]
puts "my_method_with_eval variables: #{orange}, #{lemon}, #{grapefruit}"
end
my_method_with_eval :orange => "Orange", :grapefruit => "Grapefruit"
When running that code I simply get
NameError: undefined local variable or method ‘orange’ for main:Object method my_method_with_eval in named_args_to_local_vars at line at top level in named_args_to_local_vars at line 9
Anyone got any ideas how I could simplify this down somehow so that I don't have to start my named argument methods with loads of var=args[:var] code?
Thanks,
Matthew O'Riordan
I don't believe there's any way to do this in Ruby (if anyone comes up with one, please let me know, and I'll update or delete this answer to reflect it!) - if a local variable hasn't been defined yet, there's no way to dynamically define it with the binding. You could conceivably do something like orange, lemon, grapefruit = nil before calling eval, but you may run into other problems - for instance, if args[:orange] is the string "Orange", you'll end up evaluating orange = Orange with your current implementation.
Here's something that could work, though, using the OpenStruct class from the standard library (by "could work", I mean "it's up to your sense of style whether a.orange is any nicer than args[:orange]"):
require 'ostruct'
def my_method_with_ostruct(args)
a = OpenStruct.new(args)
puts "my_method_with_ostruct variables: #{a.orange}, #{a.lemon}, #{a.grapefruit}"
end
If you don't need easy access to any state or methods on the receiver of this method, you could use instance_eval, as follows.
def my_method_with_instance_eval(args)
OpenStruct.new(args).instance_eval do
puts "my_method_with_instance_eval variables: #{orange}, #{lemon}, #{grapefruit}"
end
end
You could even do something tricky with method_missing (see here for more) to allow access to the "primary" object, but the performance probably wouldn't be great.
All in all, I think it's probably most straightforward/readable to go with the less DRY initial solution that bothered you.
Merge of Greg's and Sand's answers:
require 'ostruct'
def my_method(args = {})
with args do
puts a
puts b
end
end
def with(args = {}, &block)
OpenStruct.new(args).instance_eval(&block)
end
my_method(:a => 1, :b => 2)
I found a discussion on this on ruby-talk-google and it seems to be an optimisation of the parser. Local variables are already figured out at runtime so that local_variables is already set at the beginning of the method.
def meth
p local_variables
a = 0
p local_variables
end
meth
# =>
[:a]
[:a]
That way Ruby doesn’t need to decide whether a is a method or a local variable or whatnot at runtime but can safely assume it is a local variable.
(For comparison: In Python locals() would be empty at the beginning of the function.)
At my blog (see link in user info), I just tried to address handling this problem neatly. I go into more detail there, but the core of my solution is the following helper method:
def collect_named_args(given, expected)
# collect any given arguments that were unexpected
bad = given.keys - expected.keys
# if we have any unexpected arguments, raise an exception.
# Example error string: "unknown arguments sonething, anyhting"
raise ArgumentError,
"unknown argument#{bad.count > 1 ? 's' : ''}: #{bad.join(', ')}",
caller unless bad.empty?
Struct.new(*expected.keys).new(
*expected.map { |arg, default_value|
given.has_key?(arg) ? given[arg] : default_value
}
)
end # def collect_named_args
which is called as follows:
def foo(arguments = {})
a = collect_named_args(arguments,
something: 'nothing',
everything: 'almost',
nothing: false,
anything: 75)
# Do something with the arguments
puts a.anything
end # def foo
I'm still trying to figure out if there is any way to get my results into local_variables or not - but as others have noted, Ruby doesn't want to do that. You could use the "with" trick, I suppose.
module Kernel
def with(object, &block)
object.instance_eval &block
end
end
then
with(a) do
# Do something with arguments (a)
put anything
end
but that feels unsatisfactory for several reasons.
I like the above solution because it uses a Struct instead of an OpenStruct, which means one less require, and what you get back is set as far as what variables are being handled.
This doesn't solve the problem, but I tend to do
orange, lemon, grapefruit = [:orange, :lemon, :grapefruit].
map{|key| args.fetch(key)}
as it's pretty easy to copy and paste the orange lemon grapefruit bit.
If you find the colons too much work, you could do
orange, lemon, grapefruit = %w{orange, lemon, grapefruit}.
map{|str| str.gsub(",", "").to_sym}.map{|key| args.fetch(key)}
I found myself wondering how to do this myself today. Not only would I like to DRY up my code, but I'd like to have argument validation, too.
I came across a blog post by Juris Galang where he's explained a couple ways of handling it. He's has published a gem that encapsulates his ideas which looks interesting.

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