Swiftpack.co - Package - johnfairh/RubyGateway


CI codecov Carthage compatible Pod Platforms License

Embed Ruby in Swift: load Gems, run Ruby scripts, get results.

RubyGateway is a framework built on the Ruby C API that lets Swift programs running on macOS or Linux painlessly and safely run and interact with Ruby programs. It's easy to pass Swift datatypes into Ruby and turn Ruby objects back into Swift types.

The current version of the framework entirely covers calling Ruby from Swift, including passing Swift closures as blocks. Support for calling Swift from Ruby is slowly improving: the most recent version supports global functions, and adding custom classes and methods should be in the next release.

See CRuby if you are looking for a low-level Ruby C API wrapper.



Rouge is a code highlighter. In Ruby:

require 'rouge'
html = Rouge.highlight("let a = 3", "swift", "html")

In Swift 4.2 with similar [lack of] error checking:

import RubyGateway

try! Ruby.require(filename: "rouge")
let html = try! Ruby.get("Rouge").call("highlight", args: ["let a = 3", "swift", "html"])

Or using dynamic member lookup:

import RubyGateway

try! Ruby.require(filename: "rouge")
let html = try! Ruby.Rouge!.call("highlight", args: ["let a = 3", "swift", "html"])


// Create an object.  Use keyword arguments with initializer
let student = RbObject(ofClass: "Academy::Student", kwArgs: ["name": "barney"])!

// Acess an attribute
print("Name is \(student.get("name"))")

// Fix their name by poking an ivar
try! student.setInstanceVar("@name", newValue: "Barney")

// Get a Swift version of `:reading`
let readingSubject = RbSymbol("reading")

// Call a method with mixed Swift data types
try! student.call("add_score", args: [readingSubject, 30])
try! student.call("add_score", args: [readingSubject, 35])

// Get a result as floating point
let avgScoreObj = try! student.call("mean_score_for_subject", args: [readingSubject])
let avgScore = Double(avgScoreObj)!
print("Mean score is \(avgScore)")

// Pass Swift code as a block
let scores = student.all_scores!
scores.call("each") { args in
    print("Subject: \(args[0]) Score: \(args[1])")
    return .nilObject

// Convert to a Swift array
let subjects = Array<String>(student.all_subjects!)
subjectsPopularityDb.submit(subjects: subjects)

Dynamic data exchange

Global variables:

// epochStore.current: Int

        name: "$epoch",
        get: { epochStore.current },
        set: { epochStore.current = newEpoch })

Global functions:

let logArgsSpec = RbMethodArgsSpec(leadingMandatoryCount: 1,
                                   optionalKeywordValues: ["priority" : 0])
try Ruby.defineGlobalFunction(name: "log",
                              argsSpec: logArgsSpec) { _, method in
    Logger.log(message: String(method.args.mandatory[0]),
               priority: Int(method.args.keyword["priority"]!))
    return .nilObject

Calls from Ruby:

log(object2_to_log, priority: 2)



  • Swift 4.2 or later, from swift.org or Xcode 10.0+
  • macOS (tested on 10.14.2) or Linux (tested on Ubuntu Bionic/18.04 on x86_64) with Clang 6.
  • Ruby 2.2 or later including development files:
    • For macOS, these come with Xcode.
    • For Linux you may need to install a -dev package depending on how your Ruby is installed.
    • RubyGateway requires 'original' MRI/CRuby Ruby - no JRuby/Rubinius/etc.


For macOS, if you are happy to use the system Ruby then you just need to include the RubyGateway framework as a dependency. If you are building on Linux or want to use a different Ruby then you also need to configure CRuby.

Getting the framework

Carthage for macOS:

github "johnfairh/RubyGateway"

Swift package manager for macOS or Linux:

.package(url: "https://github.com/johnfairh/RubyGateway", from: "2.1.0")

CocoaPods for macOS:

pod 'RubyGateway'

Configuring CRuby

CRuby is the glue between RubyGateway and your Ruby installation. It is a separate github project but RubyGateway includes it as submodule so you do not install or require it separately.

By default it points to the macOS system Ruby. Follow the CRuby usage instructions to change this. For example on Linux using Brightbox Ruby 2.5:

sudo apt-get install ruby2.5 ruby2.5-dev pkg-config
mkdir MyProject && cd MyProject
swift package init --type executable
vi Package.swift
# add RubyGateway as a package dependency (NOT CRuby)
# add RubyGateway as a target dependency
echo "import RubyGateway; print(Ruby.versionDescription)" > Sources/MyProject/main.swift
swift package update
swift package edit CRuby
Packages/CRuby/cfg-cruby --mode pkg-config --name ruby-2.5
PKG_CONFIG_PATH=$(pwd)/Packages/CRuby:$PKG_CONFIG_PATH swift run


Welcome: open an issue / johnfairh@gmail.com / @johnfairh


Distributed under the MIT license.


Stars: 52
Help us keep the lights on


Used By

Total: 0


v2.0.0 - Oct 8, 2018

  • Require Swift 4.2.
  • Dynamic member lookup for property access or 0-arg methods.
  • Global variables can use native Swift types.

v1.1.0 - Jul 18, 2018


  • Add RbComplex wrapper for Ruby Complex.
  • Add RbRational wrapper for Ruby Rational.
  • Add RbGateway.defineGlobalVar - dynamically implement Ruby global variables in Swift.

v1.0.0 - May 11, 2018

  • Add RbGateway.taintChecks.
  • Full SemVer rules from now on.

v0.5.0 - May 5, 2018

  • Change kwArgs to use DictionaryLiteral per dynamic callable.
  • Add conditional Set RbObjectConvertible conformance.
  • Add conditional ArraySlice RbObjectConvertible conformance.

v0.4.0 - Apr 20, 2018

  • Now requires Swift 4.1 (conditional conformances!).
  • Replace RbObject's deprecated CustomPlaygroundQuickLookable conformance with CustomPlaygroundDisplayConvertible.
  • Add conditional Array RbObjectConvertible conformance.
  • Add conditional Dictionary RbObjectConvertible conformance.
  • Add RbThread utilities and write up rules for multithreading.
  • Add conditional Range family RbObjectConvertible conformance.
  • Add RbObjectCollection to use Swift collection protocols with Ruby.
  • Allow Swift nil literal in argument positions to mean Ruby nil.