Expressiveness meets Performance with C Extensions
This advanced program demonstrates how Ruby's expressiveness and flexibility can be combined with C's raw performance through Foreign Function Interface (FFI) and native extensions for optimal results.
#!/usr/bin/env ruby
# Advanced Tier: Ruby + C Extension Integration
# This program demonstrates Ruby calling C extensions for performance
# Use case: Ruby's expressiveness with C's speed for critical paths
require 'fiddle'
require 'fiddle/import'
require 'benchmark'
# Simulated C Extension (in real world, would be compiled C shared library)
module CExtension
extend Fiddle::Importer
# In production, this would load actual compiled C extension:
# dlload './native_extension.so'
# Mock C functions for demonstration
class << self
def fast_fibonacci(n)
# Simulates what would be a C implementation
a, b = 0, 1
n.times { a, b = b, a + b }
a
end
def fast_prime_check(n)
return false if n < 2
return true if n == 2
return false if n.even?
(3..Math.sqrt(n).to_i).step(2) do |i|
return false if n % i == 0
end
true
end
def fast_array_sum(arr)
# C would use pointer arithmetic
arr.reduce(0.0, :+)
end
end
end
# Ruby + C Integration Orchestrator
class RubyCIntegration
attr_reader :results
def initialize
@results = []
end
# Benchmark computation in both languages
def benchmark(operation_name, ruby_block, c_block, input)
puts "⚡ #{operation_name}:"
# Ruby execution
ruby_time = Benchmark.measure { @ruby_result = ruby_block.call }.real
# C extension execution
c_time = Benchmark.measure { @c_result = c_block.call }.real
@results << {
operation: operation_name,
ruby_time: ruby_time,
c_time: c_time,
speedup: ruby_time / c_time
}
puts " Ruby: #{(ruby_time * 1000).round(3)}ms"
puts " C: #{(c_time * 1000).round(3)}ms"
puts " Speedup: #{(ruby_time / c_time).round(2)}x"
puts
end
# Demonstrate Ruby's metaprogramming with C performance
def define_optimized_method(method_name, c_implementation)
# Ruby metaprogramming: define methods dynamically
self.class.define_method(method_name) do |*args|
# Route to C extension for performance
c_implementation.call(*args)
end
end
# Ruby's blocks with C's speed
def parallel_process(items, &block)
# In real world, could use C extension for parallel processing
# while keeping Ruby's elegant block syntax
items.map do |item|
{
item: item,
result: block.call(item),
processed_by: 'C Extension'
}
end
end
end
def main
puts '=' * 60
puts '💎 + 🔧 RUBY + C INTEGRATION'
puts 'Advanced Tier: Expressiveness meets Performance'
puts '=' * 60
puts
integration = RubyCIntegration.new
# Benchmark: Fibonacci, Prime checking, Array operations
fib_n = 30
integration.benchmark(
"Fibonacci(#{fib_n})",
-> { fibonacci_ruby(fib_n) },
-> { CExtension.fast_fibonacci(fib_n) },
fib_n
)
puts '=' * 60
puts '🎨 RUBY ELEGANCE + C PERFORMANCE'
puts '=' * 60
puts
# Demonstrate metaprogramming
integration.define_optimized_method(:optimized_fib,
->(n) { CExtension.fast_fibonacci(n) })
puts "Using dynamically defined method:"
puts " optimized_fib(20) = #{integration.optimized_fib(20)}"
puts
# Ruby blocks with C backend
puts "Parallel processing with Ruby blocks + C backend:"
numbers = [7, 11, 13, 17, 19, 23, 29, 31]
results = integration.parallel_process(numbers) do |num|
CExtension.fast_prime_check(num)
end
results.each do |result|
status = result[:result] ? 'prime' : 'composite'
puts " #{result[:item]}: #{status}"
end
puts
puts '✨ Languages Used:'
puts ' 💎 Ruby - Metaprogramming, blocks, elegant syntax'
puts ' 🔧 C - Performance, low-level operations'
puts ' 🔗 FFI - Foreign Function Interface'
end
main if __FILE__ == $0
Rails with C extensions for JSON parsing, HTTP servers
Ruby DSLs with C-powered heavy computations
Ruby scripting with C engine for graphics and physics
Elegant Ruby interfaces to high-performance C libraries