The Useful Things you can do with Ruby thread


Richard Marks:
The Useful Things you can do with Ruby thread

Thing #1. OpenStruct
OpenStruct allows you to create data objects and set arbitrary attributes. For example:

require 'ostruct'

record =    = "John Smith"
record.age     = 70
record.pension = 300

puts     # -> "John Smith"
puts record.address  # -> nil

It is like a hash with a different way to access the data. In fact, it is implemented with a hash, and you can initialize it with one.


hash = { "country" => "Australia", :population => 20_000_000 }
data =

p data # -> <OpenStruct country="Australia" population=20000000>

If you find anything useful that you can do with Ruby, that is not already listed here, please make a reply to this thread with your findings. Please do not include any links to external websites on this thread unless you are linking to a library or something such as that.

Built-in printf-style strings.

eg. Convert FF to decimal

"%d" % 0xFF

eg. Convert 255 to hex

"%x" % 255


dollar = 1
cents = 9
result = "You have %d dollars and %d cents" % [dollar,cents]
puts result


[0] Message Index