Ruby – Executable Class Bodies

It is possible for a class to be used in the style of a method.

Here’s an example:

total_sum = class SimpleSum
  sum_of_two_numbers = 7 + 3
  sum_of_two_numbers
end

puts total_sum
puts SimpleSum.superclass

This outputs:

PS C:\Temp\irb> ruby .\simplesum.rb
10
Object
PS C:\Temp\irb>

It is very unlikely that you will need to classes in this way in real life. But it is possible if you need to.