How is the Ruby safe navigation (&.) implemented? - ruby

I was trying to figure out how the safe navigation operator is implemented but didn't find the source for it, would love to know how it works and how efficient it is.

The safe navigation operator was implemented following Feature #11537.
It is part of Ruby's core langiage, i.e. is implemented in the language parser, has an op code in the virtual machine. Thus, there is no single place where the operator is implemented. The first version of it was added in commit a356fe1c but it has seen multiple extensions since then.
As for how efficient it is, the answer is probably: quite. You might want to run your own benchmarks however to confirm whether it suits your requirements.

Before the safe navigation operator was implemented into the core language using C, there used to be a gem with similar functionality called andand. If you want to research how something like this could be implemented using Ruby, then the andand source is a good place to start:
https://github.com/raganwald/andand
require 'andand'
nil.andand.some_method
=> nil

Related

Is receive(:method).never completely equivalent to not_to receive(:method)

Using RSpec 3.7.0. I would like to know whether writing
expect(instance).not_to receive(:method)
is completely identical to writing
expect(instance).to receive(:method).never
or if there are any (even subtle) differences or side effects.
As per this link https://github.com/rspec/rspec-mocks/issues/895
You can use either of these to cause an example to fail if a method is called
Author #myronmarston also provided an example

Modifying core classes in a gem

I'm developing a Gem which I think will be useful for more people than just me. One issue I'm facing is that I need to merge nested hashes. I found this useful Gist to accomplish that, but now I'm wondering if it's okay to modify Hash# like this in a Gem?
I'm sure there's a community "standard" or best practices that either accepts or declines this sort of code, so I'm turning to SO for guidance.
Thank you.
When in doubt, just subclass Hash and include the Module in your subclass. You should particularly do this, when you override methods or change the behavior dramatically.
But i don't see why you shouldn't just modify the Hash class. Rails, for example, extends Core classes rigorously and i've never heard someone complain. You might take a look at how Rails' activesupport extends core classes:
https://github.com/rails/rails/tree/master/activesupport/lib/active_support/core_ext
Just make sure not to break existing behavior, so the users of your gem will not experience unwanted side-effects.
You should always have a good reason for extending core class. I'd say that deep merging is good enough reason. To add new Hash method for deep merging like Hash#deep_merge - why not.
But I don't believe it justifies modifying existing method - overriding Hash#merge to support deep merge. People expect this method to behave certain way and if it suddenly behaves differently after requiring your gem, they won't like it. If you absolutely must do it, describe it at the prominent place in your documentation.
UPDATE: just read the comments under the other answer. Yeah, best solution in this case is simply to include activesupport/lib/active_support/core_ext/hash/deep_merge :)

Do ruby gems ever conflict?

As a ruby newbie, I was wondering, will gems ever conflict with eachother? For example, if 2 gems overrode the << method on array, which would win, or is there something to stop this?
Thanks
I assume you are talking about redefining methods, not overriding them, right? If two libraries overrode the same method in two different subclasses, there wouldn't be any problem.
If two or more libraries redefine the same method, then whichever one happens to be loaded last wins. In fact, this is actually no different than just one library redefining a method: the Ruby interpreter provides an implementation of Array#<< for you, and if you redefine it, your definition wins, simply because it came later.
The best way to stop this is simple: don't run around screwing with existing methods. And don't use libraries that do. The -w commandline flag to enable warnings is very helpful there, since at least in Ruby 1.9.2 it prints a warning if methods get redefined.
In Ruby 2.0, there will probably be some kind of mechanism to isolate method (re-)definitions into some kind of namespace. I wouldn't hold my breath, though: these so-called selector namespaces have been talked about in the Ruby community for almost 10 years now, and in the Smalltalk community even longer than that, and AFAIK nobody has ever produced a working implementation or even a working design for Ruby. A newer idea is the idea of Classboxes.
As far as I can tell, you're talking about monkeypatching (also known as duck punching in the ruby community).
This article has another example of monkeypatching (and other practices) gone bad.
In practice, no, though you could probably construct a situation like that if you really tried. Here's an interesting article (though old) that explains how this could happen.
If two gems "overrode the << method on array" they would need to be subclassing Array, and those classes would have different names or be in different modules.

What are the things you would like improved in the Ruby language?

What are the things you wish Ruby (and more generally the Ruby community) would improve?
I read somewhere that Ruby is the love-child of Smalltalk and LISP, with Miss Perl as the Nanny.
I have a lot of respect for Ruby's parents, but I'm not sure I like the influence Miss Perl had on the child. Specifically, I don't like the predefined variables: I need a cheat sheet to know what they mean. You could say "just don't use them". Well, I don't... but other people do. And when I download a plugin on the Web, I have no choice but to fetch my cheat-sheet if I ever need to go and touch the source code. I just wish they would remove those from the language itself.
Also, I think that Ruby is too much of a moving target. My code breaks on every new Ruby upgrade, even on minor releases. This is true also of Ruby on Rails and most Rails plugins I have worked with: they just change all the time, and nobody seems to care whether the changes break everything or not. IMHO, although I love a lot of things in Ruby, this lack of stability is almost a show-stopper.
I wish people would consider backward compatibility between minor releases as an unbreakable rule when releasing a new language (or library or framework) version.
I wish that some of the lesser used modules of the standard library were documented.
Make require-ing files less painful. Don't ask me how, but maybe have one file dedicated to knowing the paths involved and just get rid of the relative path crud from everything else.
Getting rid of the artificial distinction between Modules and Classes would be nice.
Both Modules and Classes are Namespaces. Modules are also Mixins, while Classes aren't. Classes can also be instantiated while Modules can't. This distinction is unnecessary. Just get rid of Modules and allow Classes to be used as Mixins.
An example of a language where this works is Newspeak.
I'd appreciate being able to install ruby 1.9 as an RPM rather than having to use the source.
Make Ruby completely Message Sending based, get rid of everything that is not a message send: local variables, global variables, instance variables, class hierarchy variables, constants, magic globals, magic constants, builtin operators, builtin keywords, even literals. See Self, Ioke or Newspeak for the incredible power and elegance this gains.
I wish they would get rid of the predefined variables: $!, $&, $+, etc.
I would like to have support for static compile-time metaprogramming. The Converge Programming Language might be a good starting point.
Replace the Mixin system with a Traits system.
Replace Exceptions with a Common Lisp style Conditions system.

Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?

I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?
BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done".
No it's not a best practice. The best analogy to assert() in Ruby is just raising
raise "This is wrong" unless expr
and you can implement your own exceptions if you want to provide for more specific exception handling
I think it is totally valid to use asserts in Ruby. But you are mentioning two different things:
xUnit frameworks use assert methods for checking your tests expectations. They are intended to be used in your test code, not in your application code.
Some languages like C, Java or Python, include an assert construction intended to be used inside the code of your programs, to check assumptions you make about their integrity. These checks are built inside the code itself. They are not a test-time utility, but a development-time one.
I recently wrote solid_assert: a little Ruby library implementing a Ruby assertion utility and also a post in my blog explaining its motivation. It lets you write expressions in the form:
assert some_string != "some value"
assert clients.empty?, "Isn't the clients list empty?"
invariant "Lists with different sizes?" do
one_variable = calculate_some_value
other_variable = calculate_some_other_value
one_variable > other_variable
end
And they can be deactivated, so assert and invariant get evaluated as empty statements. This let you avoid performance problems in production. But note that The Pragmatic Programmer: from journeyman to master recommends against deactivating them. You should only deactivate them if they really affect the performance.
Regarding the answer saying that the idiomatic Ruby way is using a normal raise statement, I think it lacks expressivity. One of the golden rules of assertive programming is not using assertions for normal exception handling. They are two completely different things. If you use the same syntax for the two of them, I think your code will be more obscure. And of course you lose the capability of deactivating them.
Some widely-regarded books that dedicate whole sections to assertions and recommend their use:
The Pragmatic Programmer: from Journeyman to Master by Andrew Hunt and David Thomas
Code Complete: A Practical Handbook of Software Construction by Steve McConnell
Writing Solid Code by Steve Maguire
Programming with
assertions
is an article that illustrates well what assertive programming is about and
when to use it (it is based in Java, but the concepts apply to any
language).
What's your reason for adding the assert method to the Kernel module? Why not just use another module called Assertions or something?
Like this:
module Assertions
def assert(param)
# do something with param
end
# define more assertions here
end
If you really need your assertions to be available everywhere do something like this:
class Object
include Assertions
end
Disclaimer: I didn't test the code but in principle I would do it like this.
It's not especially idiomatic, but I think it's a good idea. Especially if done like this:
def assert(msg=nil)
if DEBUG
raise msg || "Assertion failed!" unless yield
end
end
That way there's no impact if you decide not to run with DEBUG (or some other convenient switch, I've used Kernel.do_assert in the past) set.
My understanding is that you're writing your own testing suite as a way of becoming more familiar with Ruby. So while Test::Unit might be useful as a guide, it's probably not what you're looking for (because it's already done the job).
That said, python's assert is (to me, at least), more analogous to C's assert(3). It's not specifically designed for unit-tests, rather to catch cases where "this should never happen".
How Ruby's built-in unit tests tend to view the problem, then, is that each individual test case class is a subclass of TestCase, and that includes an "assert" statement which checks the validity of what was passed to it and records it for reporting.

Resources