Sha256: fbc806739ae77f08e2876ed1d3a945c946b28a213e050cf95f732e2ab395a48f

Contents?: true

Size: 1.02 KB

Versions: 26

Compression:

Stored size: 1.02 KB

Contents

class String

  # Evaluates a String as a Proc.
  #
  #   xyp = "|x,y| x + y".to_proc
  #   xyp.class      #=> Proc
  #   xyp.call(1,2)  #=> 3
  #
  #--
  # Note: Sure would be nice if this could
  # grab the caller's context!
  #++
  def to_proc(context=nil)
    if context
      if context.kind_of?(Binding) or context.kind_of?(Proc)
        Kernel.eval "proc { #{self} }", context
      else context
        context.instance_eval "proc { #{self} }"
      end
    else
      Kernel.eval "proc { #{self} }"
    end
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCString < Test::Unit::TestCase

    def test_to_proc
      assert_nothing_raised { @add = '|x,y| x + y'.to_proc }
      assert_equal(4, @add.call(2,2))    
      @t = 3
      @multi = '|y| @t * y'.to_proc(self)
      assert_equal(6, @multi.call(2))
      x = 4
      @div = '|y| x / y'.to_proc(binding)
      assert_equal(2, @div.call(2))
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/string/to_proc.rb
facets-1.0.3 packages/core/lib/facet/string/to_proc.rb
facets-1.0.0 lib/facet/string/to_proc.rb
facets-1.2.1 lib/facets/core/string/to_proc.rb
facets-1.1.0 lib/facet/string/to_proc.rb
facets-1.2.0 lib/facets/core/string/to_proc.rb
facets-1.3.0 lib/facets/core/string/to_proc.rb
facets-1.3.2 lib/facets/core/string/to_proc.rb
facets-1.3.3 lib/facets/core/string/to_proc.rb
facets-1.3.1 lib/facets/core/string/to_proc.rb
facets-1.4.2 lib/facets/core/string/to_proc.rb
facets-1.4.0 lib/facets/core/string/to_proc.rb
facets-1.4.1 lib/facets/core/string/to_proc.rb
facets-1.4.3 lib/facets/core/string/to_proc.rb
facets-1.4.4 lib/facets/core/string/to_proc.rb
facets-1.4.5 lib/facets/core/string/to_proc.rb
facets-1.7.30 lib/facets/core/string/to_proc.rb
facets-1.7.0 lib/facets/core/string/to_proc.rb
facets-1.7.38 lib/facets/core/string/to_proc.rb
facets-1.7.46 lib/facets/core/string/to_proc.rb