Programming ≈ Fun

Written by Krešimir Bojčić

Ruby Oddities

Over the course of time I’ve noticed three peculiar Ruby behaviours. I am not saying these things are good or bad. They are a bit odd/unexpected, mostly neat and always good to know.

String concatenation

spooky =  "This " "is " "kinda" " spooky!"
puts spooky #=> This is kinda spooky!"

Default params hack

If you want to know whether your default param remained default you can do it like this:

def default_param_trick(my_param=((default=true); "default"))
  puts "param passed: #{my_param}"
  puts "default: #{default}"
end

default_param_trick
#=> param passed: default
#=> default: true

default_param_trick :foobar
#=> param passed: :foobar
#=> default:

It is really easy to explain. If you don’t pass default parameter, the part after the = gets executed. It happens to be two lines of code one of which sets default to true. Otherwise if you send a param those two lines are not executed and therefore default is not set.

The original explanation can be found at default_param_hack

Difference between do…end and {}

It has to do with precedence of the operators but the result is subtly different and sort of unexpected:

puts (1..3).map { |item| item * 2 }
#=>2
#=>4
#=>6

puts (1..3).map do |item|
  item * 2
end
#=><Enumerator:0x007f86aa84dc70>

I’ll stick to @JEG2 rule of writing brace delimiters when I care about result of block and do…end when I don’t. Except for one liners. I will always use braces for those. (The @JEG2 chooses to unfold even for one liners if the result is not important. I can see how that helps to communicate the intend, but I love one liners enough not to give up on them even if the result in not important…).