Ruby.py
Ruby wrapper for Python modules using the (PyCall gem)[https://rubygems.org/gems/pycall].
Installation
Add this line to your application's Gemfile:
gem 'ruby.py'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ruby.py
Usage
Consume a Python API in Ruby
require 'ruby.py'
string = RubyPy.import('string')
string.Formatter.new.format('The sum of 1 + 2 is {0}', 3)
#=> 'The sum of 1 + 2 is 3'
string.Template.new('$subject $object $verb')
.substitute(subject: 'S', object: 'O', verb: 'V')
#=> 'S O V'
string.capwords('this is a test')
#=> 'This Is A Test'
re = RubyPy.import('re')
m = re.match('(\w+) (\w+)', 'Isaac Newton, physicist')
m.group(0) #=> 'Isaac Newton'
m.group(1) #=> 'Isaac'
m.group(2) #=> 'Newton'
m.group(1, 2) #=> PyCall::Tuple.new('Isaac', 'Newton')
cv2 = RubyPy.import('cv2')
cv2.imread('example.png')
np = RubyPy.import('numpy')
a = np.arange(15).reshape(3, 5)
a.shape.inspect #=> '(3, 5)'
a.ndim #=> 2
a.dtype.name #=> 'int64'
a.itemsize #=> 8
a.size #=> 15
tf = RubyPy.import('tensorflow')
sess = tf.Session.new
a = tf.placeholder tf.int16
b = tf.placeholder tf.int16
add = tf.add(a, b)
mul = tf.multiply(a, b)
result = sess.run(add, feed_dict: { a => 2, b => 3 })
Enhance a Python API in Ruby
require 'ruby.py'
# Top-level module to expose Python 'tensorflow' API to Ruby.
TensorFlow = RubyPy.import('tensorflow')
# Enhance the module's Ruby API.
module TensorFlow
# Pass a tf.Session() to a block and auto-close it.
def self.session(*args, &block)
return(s = self.Session.new(*args)) unless block
begin; yield(s); ensure; s.close; end
end
end
Support
Open an issue via GitLab or email [email protected].
Contributing
Development
After checking out the repo, run bin/setup
to install
dependencies. Then, run rake spec
to run the tests. You can also run
bin/console
for an interactive prompt that will allow you to experiment.
To test with an arbitrary version of pycall set the environment variable
RUBYPY_PYCALL
to specify the version and re-bundle. E.g.
$ export RUBYPY_PYCALL="1.1.0.rc1"
$ bundle install
$ bundle exec rake spec
To install this gem onto your local machine, run bundle exec rake
install
. To release a new version, update the version number in
ruby.py.gemspec
, and then run bundle exec rake release
, which will
create a git tag for the version, push git commits and tags, and push the
.gem
file to rubygems.org.
License
The gem is available as open source under the terms of the MIT License.