Method: TNetstring.dump
- Defined in:
- lib/tnetstring.rb
.dump(obj) ⇒ Object
Constructs a tnetstring out of the given object. Valid Ruby object types include strings, integers, boolean values, nil, arrays, and hashes. Arrays and hashes may contain any of the previous valid Ruby object types, but hash keys must be strings.
Example
int = 12345
TNetstring.dump(int)
#=> '5:12345#'
hash = {'hello' => 'world'}
TNetstring.dump(hash)
#=> '16:5:hello,5:world,}'
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/tnetstring.rb', line 146 def self.dump(obj) if obj.kind_of?(Integer) int_str = obj.to_s "#{int_str.length}:#{int_str}#" elsif obj.kind_of?(Float) float_str = obj.to_s "#{float_str.length}:#{float_str}^" elsif obj.kind_of?(String) || obj.kind_of?(Symbol) "#{obj.length}:#{obj}," elsif obj.is_a?(TrueClass) "4:true!" elsif obj.is_a?(FalseClass) "5:false!" elsif obj == nil "0:~" elsif obj.kind_of?(Array) dump_list(obj) elsif obj.kind_of?(Hash) dump_dictionary(obj) else assert false, "Object must be of a primitive type: #{obj.inspect}" end end |