15 Weird Things About Ruby That You Should Know

15 Weird Things About Ruby That You Should Know

By Jesus Castello

Ruby is an amazing language with a lot of interesting details that Clinica Stomatologie Bucuresti curs valutar crama lechinta Psiholog Cluj you may not have seen before...

…in this post I compiled some of those details for your own enjoyment in a nice-looking list :)

1

Heredoc + Method

If you have some data that you want to embed into your program you may want to use a “heredoc”.

Like this:

input = <<-IN
ULL
RRDDD
LURDL
IN

This will give you a string. But you may want to do some post-processing, like splitting this string into an array of strings.

Ruby lets you do this:

input = <<-IN.split
ULL
RRDDD
LURDL
IN

Bonus tip:
Ruby 2.3 introduced the "squiggly heredoc" <<~. This will remove all the extra spaces introduced by indentation, which is a common problem when using heredocs for text.

2

Call a Method Using Double Colon

Apparently this is a thing…

"abc"::size
# 3
 
[1,2,3,4,5]::size
# 5
3

Puts with Multiple Arguments

Pretty simple, but could be useful in some situations I guess.

puts 1,2,3
1
2
3
4

Infinite Indexing

Example:

words = ["abc", "foo"]
words[0][0][0][0][0]

This works because [] is just a method & it keeps returning the first character, which is also a string.

5

De-structuring Block Arguments (or whatever you want to call this)

Want to get rid of some local variables? You will love this trick!

a = [[1,2],[3,4]]
 
a.each do |(first, last)|
  # ...
end

This has the same effect as if we did this:

a = [[1,2],[3,4]]
 
a.each do |sub_array|
 first, last = sub_array
 # ...
end

But it saves you one line of code 🙂

6

Special Global Variables

When you use a regular expression with capture groups it will set the global variable $1 to the first group, $2 for the second group, etc.

The thing about these is that they don't behave like normal variables. They are ‘method-local’ & ‘thread-local’, as described by the documentation.

Also they can’t be directly assigned to like regular global variables.

$1 = 'test'
# SyntaxError: (eval):2: Can't set variable $1
7

Shovel Method on Strings

There is this “shovel” method on string which doesn’t do what you would expect when you use it with a number…

"" << 97
# a

…it’s interpreting the number as an ASCII character.

Here’s another way to do that:

97.chr
# a
8

Character Literals

Not sure if there are any practical uses for this one…

?a
"a"
 
?aa
# Syntax error

Let me know in the comments what you think 🙂

9

The RbConfig Module

RbConfig is a module which is not documented & it contains some info about your Ruby installation.

RbConfig.constants
[:TOPDIR, :DESTDIR, :CONFIG, :MAKEFILE_CONFIG]

There is some useful info under RbConfig::CONFIG (like compile flags, ruby version & operating system).

RbConfig::CONFIG['host_os']
# "linux-gnu"
 
RbConfig::CONFIG['ruby_version']
# "2.4.0"
10

Spaces, Spaces Everywhere!

You can put as many spaces as you want between a method call & the receiver of that call.

a = [1,2,3]
 
a    [0]
a .size
a   . empty?

Yes, this is valid Ruby syntax 🙂

11

Infinite Nesting of Constants

You can have an infinite amount of nested constants like this:

String::String::Fixnum::Float

The reason this works is that all top-level constants (defined outside any class) are contained in the Object class & every class inherits from Object by default.

Try Object.constants to see what I mean.

12

Chaining the Shovel Operator

You can chain the shovel << operator multiple times:

a = []
 
a << 1 << 2 << 3
 
# a = [1, 2, 3]
13

BEGIN & END

Two keywords that you don’t see very often are BEGIN & END. I believe these come from the Perl / Unix world, where it’s common to write short scripts for processing output from other programs.

Let’s see an example of how this works:

puts 123
 
BEGIN {
  puts "Program starting..."
}

This code will print "Program starting..." before it prints 123. It could be useful if you are writing the kind of short scripts that this is meant for, but probably not very useful in web applications.

Update:
Reader Ronald sent me some interesting uses for this trick. Here is what he said:

"It is very useful, for example for fiddling with the RUBYLIB path for the 'require' statements, because it is guaranteed to be executed before all the 'require'. I also use it to set $VERBOSE to true, or set some environment variables, etc."

14

Flip-Flop

I don’t even know why this is a thing, but I would advice to stay away from it because it can be confusing & most people are not familiar with this feature

But it could be useful to know in case you find this in other people’s code.

This is the syntax:

if (condition)..(condition)
  # do something
end

The idea is that once the first condition is true an invisible “switch” will turn on & everything from there will evaluate as true until the 2nd condition is true.

Example:

(1..20).each do |i|
  puts i if (i == 3)..(i == 15)
end

This prints all the numbers from 3 to 15, but if you skip 15 it will keep printing.

15

Redo Keyword

Another keyword that you don’t see very often is redo, this allows you to repeat the same iteration inside a loop…

10.times do |n|
  puts n
  redo
end

…but unless you use next or break you will have an infinite loop. So I think you should not use this feature.

Conclusion

You learned about a few cool Ruby tricks & tips. If you want more see my other post here.

Don’t forget to share this post so more people can see it!

Popular posts