All Posts in “Stackoverflow”

StackOverflow cool Ruby questions 4

Welcome to the fourth post of this series. Just before proceeding to the questions, I would like to mention the great Metaprogramming Ruby: Program Like the Ruby Pros book by Paolo Perrotta, a very good book that explains the metaprogramming aspects of the Ruby language.
Now let’s get going!

Scope gates

Taken from the above mentioned book:

There are exactly three places where a program leaves the previous scope behind and opens a new one:
• Class definitions • Module definitions • Methods
Scope changes whenever the program enters (or exits) a class or module definition or a method. These three borders are marked by the keywords class, module, and def, respectively. Each of these keywords acts like a Scope Gate.

The question title is: Closure doesn’t work

The question text is:
If block is a closure, why this code does not work? And how to make it work?

The answer is:
Blocks are closures and arg is indeed available inside the Class.new block. It’s just not available inside the foo method because def starts a new scope. If you replace def with define_method, which takes a block, you’ll see the result you want:

Almost everything in Ruby is an object

The question title is: Examples of ‘Things’ that are not Objects in Ruby

The question text is:
“Everything is an object” was one of the first things I learned about Ruby, but in Peter Cooper’s Beginning Ruby: From Novice to Professional book, it is mentioned that “almost everything in Ruby is an object”.

Can you give me some examples of things that are not objects in Ruby?

The answer is:
he most obvious one that jumps into my head would be blocks. Blocks can be easily reified to a Proc object, either by using the &block parameter form in a parameter list or by using lambda, proc, Proc.new or (in Ruby 1.9) the “stabby lambda” syntax. But on its own, they aren’t objects.

Another example are built in operators: while methods are objects, some operators are not implemented as methods (and, or &&, ||), so those operators aren’t objects.

Hash keys

The idea here is that whenever you want to define your own keys types for Ruby hashes, then you need to define 2 methods #eq? and #hash for those types.

The question title is: How to make object instance a hash key in Ruby?

The question text is:
I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be ‘equal’. I’d then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.

f1 and f2 should be equal at this point.

should print 8

The answer is:
See http://ruby-doc.org/core/classes/Hash.html

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash

Kernel#abort

The question title is: Ruby – Exit Message

The question text is:
Is there a one line function call that quits the program and displays a message? I know in Perl its as simple as this:

Essentially I’m just tired of typing this:

The answer is:
The ‘abort’ function does this. For example:

StackOverflow cool Ruby questions 3

Welcome to the third post of this series. Just before diving into the new questions’ set, I want to mention a little script that I wrote to notify the user when a new question is posted on Stackoverflow, it works on Mac and uses growl.
Now let’s proceed to questions:

Relationship between the metaclass of base and derived classes

The question title is: What is the relationship between the metaclass of Base and Derived class in Ruby?

The question text is:

In Ruby, we could use super within singleton method to call the corresponding super class’s singleton method, like the following code shows.

However, I don’t seem quite get how that call to super within Derived.class_method could reach Base.class_method. I’d assume that class_method is defined on their metaclass, does that mean their metaclass has parent/child relationship? (I can’t quite confirm that by experiments)

I’m asking this question because I remembered seeing somewhere there’s some kind of relationship between base and derived class’ metaclass (but I can’t find it any more). In addition to know how actually super works, I’d also like to confirm whether the two metaclasses are totally separate or not.

The answer is:
There are four class objects in play here:

Nomenclature:

  • <...> is the class of each object.
  • The name of the class is on the second line.
  • If the name starts with #, it’s the eigenclass (aka singleton class).
  • super points to a class’s superclass
  • class points to the class’s class.

When you call Derived.class_method, Ruby follows the “right one and then up” rule: First go to the object’s class, then follow the superclass chain up, stopping when the method is found:

  • The receiver of the “class_method” call is Derived. So follow the chain right to Derived’s class object, which is its eigenclass (#Derived).
  • #Derived does not define the method, so Ruby follows the chain up the chain to #Derived’s superclass, which is #Base.
  • The method is found there, so Ruby dispatches the message to #Base.class_method

You don’t think I knew all this stuff off the top of my head, did you? Here’s where my brain got all this meta juju: Metaprogramming Ruby.

Part 2. How to make an “eigenclass” (aka “singleton class”) come out of hiding

This method will return the eigenclass of any object. Now, what about classes? Those are objects, too.

Note: Above is from Ruby1.9. When run under Ruby 1.8, you get a surprise:

Idiomatic object creation

The question title is: Idiomatic object creation in ruby

The question text is:

In ruby, I often find myself writing the following:

or even

I’m always keen to minimize boilerplate as much as possible – so is there a more idiomatic way of creating objects in ruby?

The answer is:

Struct objects are classes which do almost what you want. The only difference is, the initialize method has nil as default value for all it’s arguments. You use it like this

or

Struct has one big drawback. You can not inherit from another class.

Block vs brackets

The question title is: Using do block vs brackets {}

The question text is:

New to ruby, put on your newbie gloves.

Is there any difference (obscure or practical) between the following two snippets?

I realize the bracket syntax would allow you to place the block on one line

but outside of that are there any compelling reasons to use one syntax over the other?

The answer is:

Ruby cookbook says bracket syntax has higher precedence order than do..end
Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:

Second example only works when parentheses is used, 1.upto(3) { |x| puts x }

String and whitespace

The question title is: See if a ruby string has whitespace in it

The question text is:

I want to see if a string has any white space in it. What’s the most effective way of doing this in ruby?

Thanks

The answer is:

If by “white space” you mean in the Regular Expression sense, which is any of space character, tab, newline, carriage return or (I think) form-feed, then any of the answers provided will work:

Index of the largest value in an array

The question title is: In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?

The question text is:

If a is the array, I want a.index(a.max), but something more Ruby-like. It should be obvious, but I’m having trouble finding the answer at so and elsewhere. Obviously, I am new to Ruby.

The answer is:

For Ruby 1.8.7 or above:

It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max method anyway.

each_with_index without a block returns an enumerator that gives the item and its index. We then send max to this enumerator, which does the standard max algorithm on item-index pairs. Array.<=> is implemented so that the first item determines the ordering (unless there’s a tie, in which case the second is compared, and so on), so this works basically the same as doing max on an array of the values themselves. Then to get the index, we ask for the second item of the result (since we got a series of [value, index] pairs from each_with_index)

StackOverflow cool Ruby questions 2

Welcome in this second post of this series. Just before I list the questions of this one, I want to mention 2 things:

  • You can follow StackOverflow tagged Ruby questions on twitter using the user: sof_ruby
  • Some ppl feel shy to ask or even to answer, my (little) experience in life taught me that If you don’t ask, you don’t learn. If you don’t participate, you don’t learn. On the other side that’s the benefit of pair programming, ain’t it?

Now let’s proceed to questions:

Hash Autovivification

Hash Autovivication in simple words is the ability to do things like:

The cool idea here is that all intermediate-level hashs will be created automatically.
We can’t do that directly in Ruby, a statement like the previous one will issue an error : NoMethodError: undefined method `[]' for nil:NilClass

The question title is: ruby hash autovivification (facets)

The question text is:
Here is a clever trick to enable hash autovivification in ruby (taken from facets):

Although it works (of course), I find it really frustrating that I can’t figure out how this two liner does what it does.

The answer is:
The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.

You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.

So:

Class instance variables

This answer of this one is easy, but the idea of Class instance variables is what matters.

The question title is: Total newbie: Instance variables in ruby?

The question text is:
Pardon the total newbiew question but why is @game_score always nil?

The answer is:
Because you don’t have

The assignment in the class definition is not doing what you think it is doing, and when hit gets invoked it can’t add to nil.
If you now ask what happened to @game_score?, well, always remember Class is an object and Object is a class.
It’s way cool the way Ruby classes have this Zen-like “real” existence. Ruby doesn’t precisely have named classes, rather, class names are references to objects of class Class. By assigning to @game_score outside of an instance method you created a class instance variable, an attribute of the class object Bowling, which is an instance of class Class. These objects are not, in general, very useful. (See Chapter 1, The Ruby Way, Hal Fulton.)

You can reach the @game_score class instance variable by doing this:

(A question for you: What is the difference between class variables and class instance variables?)

Creating data structures in Ruby

I have committed a mistake myself in answering this question :P, however remember: If you don’t try, you don’t learn.

The question title is: Can the array be reinvented in Ruby?

The question text is:
This is just a hypothetical question, if you wouldn’t have the Array and the Hash class, would there be any way of implementing an Array class in pure Ruby? How?

The answer is:
Yes we can:

This works by creating instance variables @a0, @a1, etc. on the object to represent array indices 0, 1, etc. It has constant time length and index operations. The rest of the operations (remove, etc.) are a bit more effort to implement, but it’s absolutely possible.

Note that the constant time property for the index operation depends on the underlying Ruby runtime using an appropriate data structure for instance variables.

Hash#reject

The question title is: Update attributes unless blank?

The question text is:
I have an existing Project record, and I’m importing a CSV file to update the associated Project attributes. However, often the CSV will contain blank fields and I don’t want to overright exisiting attributes if the related CSV field is blank.

Something like this:

The answer is:

Ruby ‘private’ behavior

The key point here to remember is that private, protected and pulbic are just other methods defined in Ruby Module class.

The question title is: Are there good reasons for ‘private’ to work the way it does in Ruby?

The question text is:
It took me a while to understand how private methods work in Ruby, and it really strikes me as being very awkward. Does anyone know if there are good reasons for private methods to be handled the way they are? Is it just historic reasons? Or implementation reasons? Or are there good solid logical reasons (ie. semantic)?

For example:

  • Ruby’s behaviour on lines (1), (2) and (5) seems reasonable.
  • The fact that (6) is ok is a bit strange, especially coming from Java and C++. Any good reason for this?
  • I really do not understand why (3) fails ! An explanation, anyone?
  • The problem on line (4) looks like an ambiguity in the grammar, which has nothing to do with ‘private’.
  • Any ideas?

The answer is:

You might find it helpful to read ruby’s definition of public, private and protected (Skip to Access Control)

Ruby’s private is analogous to Java’s protected. There is no Ruby equivalent of Java’s private. But there are ways to fake it.

Private is defined as methods/variables that can only be called implicitly. This is why statements 2 and 3 fail. In other words, private limits methods/variables to the context of a class or subclass in which they are defined. Inheritance passes private methods to the subclasses and can therefore be accessed with an implicit self. (Explaining why statement 6 works.)

I think you’re looking for something closer to protected. Which behaves similarly to Java accessors that are not given a visibility (eg: public, private, protected) By changing the private in Spy to protected all 6 of your statements work. Protected methods can be called by any instance of the defining class or their subclasses. Either explicitly or implicitly called on self are valid statements for protected methods so long as the caller is either the class of the object responding to the call, or inherits from it.

As for statement 4. You are correct in assuming this is to avoid ambiguity. It’s more a safeguard to the potential harm of ruby’s dynamic nature. It ensures that you cannot override accessors by opening up the class again later. A situation that can arise, for example by eval’ing tainted code.

I can only speculate on he design decisions that led to these behaviours. For most of it I feel it comes down to the dynamic nature of the language.

P.S. If you really want to give things the java definition of private. Only available to the class in which it’s defined, not even subclasses. You could add an self.inherited method to your classes to remove references to the methods you want to limit access to.

Making the weight attribute inaccessible from subclasses:

It may make more sense to replace the undef_method call to something like this:

Which provides a much more helpful error and the same functionality.

The send is necessary to get around calling private methods for other classes. Only used to prove that things are actually working.

Which in hindsight, makes private and protected useless. If you’re really serious about protecting your methods you will have to override send to block them. You could also make send private.

It ends up being one of those “Damned if you do, damned if you don’t” situations. There are legitimate uses of calling send from outside an object. And overriding send requires some tricky code to account for the variable number of arguments that can be sent to any method.

That’s an exercise for another time.

Suggestions/comments regarding the content of this series are welcome! Have your say!

StackOverflow cool Ruby questions

I have participated heavily during the last 2 weeks in answering Ruby tagged questions on stackoverflow. That took place mainly after Ryan Bates tweet wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various stuff like normal questions, tricks, meta programming, best practices and language specific features.

So, I’m announcing in this post an endless series called “Stackoverflow cool Ruby questions” which will target cool Ruby questions on stackoverflow. I strongly recommend that you visit Stackoverflow on daily basis and try to participate if you have the time, but if you don’t, then I hope that you will enjoy this educational series.

There are currently more than 4,640 tagged Ruby questions, I’ll try to mix old + recent questions. I won’t cover basic questions here unless the question gets high votes. The covered questions will be related to new, tricky and controversial topics.

Please don’t hesitate to give any notes regarding the idea and the way the questions are picked and presented.

Let’s start this series, with 3 questions for this post:

‘Instance_eval’ instead of ‘yield(self)’

The question title is: Instance Eval Within Block

The question text is:

Now, how do I change this

Into this?

The answer is:

The trick here is to use instance_eval which evaluates the passed block in the context of the current object called on.

Determining whether a variable is any one of a list of values

The question title is: Shortest/most idiomatic way of determining whether a variable is any one of a list of values

The question text is:

This seems a ridiculously simple question to be asking, but what’s the shortest/most idiomatic way of rewriting this in Ruby?

I’ve previously seen this solution:

but this isn’t always functionally equivalent – I believe Array#include? actually looks to see if the variable object is contained in the list; it doesn’t take into account that the object may implement its own equality test with def ==(other).

Take, for example, Rails’ Mime::Type implementation: request.format == :html may return true, but [:html].include?(request.format) will return false, as request.format is an instance of Mime::Type, not a symbol.

The answer:
Actually, #include? does use ==. The problem arises from the fact that if you do [:a].include? foo, it checks :a == foo, not foo == :a. That is, it uses the == method defined on the objects in the Array, not the variable. Therefore you can use it so long as you make sure the objects in the array have a proper == method.

In cases where that won’t work, you can simplify your statement by removing the select statement and passing the block directly to any:

Using ‘instance_eval’ instead of ‘send’

The question title is: How to evaluate multiple methods per send command?

The question text is:

Let’s say I have an XML::Element…I want to do something like:

The answer is:

In your case it’s better to use instance_eval

And for your code: