In Ruby, can you perform string interpolation on data read from a file?

I think this might be the easiest and safest way to do what you want in Ruby 1.9.x (sprintf doesn’t support reference by name in 1.8.x): use Kernel.sprintf feature of “reference by name”. Example: >> mystring = “There are %{thing1}s and %{thing2}s here.” => “There are %{thing1}s and %{thing2}s here.” >> vars = {:thing1 => … Read more

Weird backslash substitution in Ruby

Quick Answer If you want to sidestep all this confusion, use the much less confusing block syntax. Here is an example that replaces each backslash with 2 backslashes: “some\\path”.gsub(‘\\’) { ‘\\\\’ } Gruesome Details The problem is that when using sub (and gsub), without a block, ruby interprets special character sequences in the replacement parameter. … Read more

How to access a Ruby Module method

If you include the module the method becomes an instance method but if you extend the module then it becomes a class method. module Const def format puts ‘Done!’ end end class Car include Const end Car.new.format # Done! Car.format # NoMethodError: undefined method format for Car:Class class Bus extend Const end Bus.format # Done! … Read more

call parent constructor in ruby

Ruby doesn’t have constructors, therefore it’s obviously not possible to call them, parent or otherwise. Ruby does have methods, however, and in order to call the parent’s method with the same name as the currently executing method, you can use the super keyword. [Note: super without arguments is a shortcut for passing the same arguments … Read more

What is the most efficient way to initialize a Class in Ruby with different parameters and default values?

The typical way to solve this problem is with a hash that has a default value. Ruby has a nice syntax for passing hash values, if the hash is the last parameter to a method. class Fruit attr_accessor :color, :type def initialize(params = {}) @color = params.fetch(:color, ‘green’) @type = params.fetch(:type, ‘pear’) end def to_s … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)