Features

Type Inference in RubyMine

What is the one thing that some of us like and others dislike about dynamic languages such as Ruby? It is dynamic types of course! It is a blessing and a curse. And for an IDE that claims being a Ruby IDE it is a serious task. There is a lot an IDE can help developer when working with such extremely flexible type system as Ruby’s.

We think RubyMine is the leader here. And here is why.

Local Variables Type

[code=’ruby’]
if some_cond
aaa = “string”
else
aaa = [1, 2, 3]
end

aaa. #at this point aaa is either string or array
[/code]

RubyMine knows that aaa can be one of two types, so pressing Ctrl+Space for code completion shows the list of methods corresponding to possible types.


The “…” on the right means there are more than one variations.

To see the inferred types that RubyMine sees for the variable press Ctrl+Q/^ J for Quick documentation lookup.

If we choose include?(obj) and then press Ctrl+B/⌘ B for method definition, RubyMine will confirm whether to go to array.rb or to string.rb.

Detecting for Index Variable Type

If you need to do something with the for loop index variable, RubyMine knows its type and suggests the appropriate methods.


[code=’ruby’]
range = true ? 1..10 : -10..1
for i in range do
i.succ
end
[/code]

Seeing true, false and nil

When it comes to detecting the truth RubyMine is at its best. It helps working with logical types by suggesting correctly for both TrueClass and FalseClass.

There is also a special nil object in Ruby which RubyMine knows well and treats correctly.

[code=’ruby’]
daynmb = 4 # daynum – nubmer of day of week
(1..5).include?(daynmb) ? weekend = false : weekend = true
string =
if weekend
“Hooray!”
else
nil
end

puts(string.to_s)
[/code]

to be continued: detecting Rescue type, Rails type inference and some more in the next publication…

image description

Discover more