Module: JSI::Util
- Included in:
- JSI
- Defined in:
- lib/jsi/util.rb
Constant Summary collapse
- NOOP =
a proc which does nothing
-> (*_) { }
Class Method Summary collapse
-
.ycomb ⇒ Object
this is the Y-combinator, which allows anonymous recursive functions.
Instance Method Summary collapse
- #deep_stringify_symbol_keys(object) ⇒ Object
-
#stringify_symbol_keys(hashlike) ⇒ same class as the param `hash`, or Hash if the former cannot be done
returns a version of the given hash, in which any symbol keys are converted to strings.
Class Method Details
.ycomb ⇒ Object
this is the Y-combinator, which allows anonymous recursive functions. for a simple example, to define a recursive function to return the length of an array:
length = ycomb do |len| proc { |list| list == [] ? 0 : 1 + len.call(list[1..-1]) } end
see https://secure.wikimedia.org/wikipedia/en/wiki/Fixed_point_combinator#Y_combinator and chapter 9 of the little schemer, available as the sample chapter at http://www.ccs.neu.edu/home/matthias/BTLS/
64 65 66 |
# File 'lib/jsi/util.rb', line 64 def ycomb proc { |f| f.call(f) }.call(proc { |f| yield proc { |*x| f.call(f).call(*x) } }) end |
Instance Method Details
#deep_stringify_symbol_keys(object) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/jsi/util.rb', line 35 def deep_stringify_symbol_keys(object) if object.respond_to?(:to_hash) JSI::Typelike.modified_copy(object) do |hash| out = {} (hash.respond_to?(:each) ? hash : hash.to_hash).each do |k, v| out[k.is_a?(Symbol) ? k.to_s : deep_stringify_symbol_keys(k)] = deep_stringify_symbol_keys(v) end out end elsif object.respond_to?(:to_ary) JSI::Typelike.modified_copy(object) do |ary| (ary.respond_to?(:each) ? ary : ary.to_ary).map do |e| deep_stringify_symbol_keys(e) end end else object end end |
#stringify_symbol_keys(hashlike) ⇒ same class as the param `hash`, or Hash if the former cannot be done
returns a version of the given hash, in which any symbol keys are converted to strings. behavior on collisions is undefined (but in the future could take a block like ActiveSupport::HashWithIndifferentAccess#update)
at the moment it is undefined whether the returned hash is the same
instance as the hash param. if hash is already a hash which contains
no symbol keys, this method MAY return that same instance. use #dup on
the return if you need to ensure it is not the same instance as the
argument instance.
22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/jsi/util.rb', line 22 def stringify_symbol_keys(hashlike) unless hashlike.respond_to?(:to_hash) raise(ArgumentError, "expected argument to be a hash; got #{hashlike.class.inspect}: #{hashlike.pretty_inspect.chomp}") end JSI::Typelike.modified_copy(hashlike) do |hash| out = {} hash.each do |k, v| out[k.is_a?(Symbol) ? k.to_s : k] = v end out end end |