class

First, the class << foo syntax opens up foo‘s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object. a=”foo” class << a def inspect ‘”bar”‘ end end a.inspect # => “bar” a=”foo” # new object, new singleton class a.inspect # => “foo” Now, to answer the question: … Read more

What is attr_accessor in Ruby?

Let’s say you have a class Person. class Person end person = Person.new person.name # => no method error Obviously we never defined method name. Let’s do that. class Person def name @name # simply returning an instance variable @name end end person = Person.new person.name # => nil person.name = “Dennis” # => no … Read more

How to pass command line arguments to a rake task

You can specify formal arguments in rake by adding symbol arguments to the task call. For example: require ‘rake’ task :my_task, [:arg1, :arg2] do |t, args| puts “Args were: #{args} of class #{args.class}” puts “arg1 was: ‘#{args[:arg1]}’ of class #{args[:arg1].class}” puts “arg2 was: ‘#{args[:arg2]}’ of class #{args[:arg2].class}” end task :invoke_my_task do Rake.application.invoke_task(“my_task[1, 2]”) end # … Read more

How to convert a string to lower or upper case in Ruby

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase: “hello James!”.downcase #=> “hello james!” Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest: “hello James!”.upcase #=> “HELLO JAMES!” “hello James!”.capitalize #=> “Hello james!” “hello James!”.titleize #=> “Hello James!” … Read more