What’s the difference between a string and a symbol in Ruby?

The main difference is that multiple symbols representing a single value are identical whereas this is not true with strings. For example: irb(main):007:0> :test.object_id => 83618 irb(main):008:0> :test.object_id => 83618 irb(main):009:0> :test.object_id => 83618 Those are three references to the symbol :test, which are all the same object. irb(main):010:0> “test”.object_id => -605770378 irb(main):011:0> “test”.object_id => … Read more

How to check if a URL is valid

Notice: As pointed by @CGuess, there’s a bug with this issue and it’s been documented for over 9 years now that validation is not the purpose of this regular expression (see https://bugs.ruby-lang.org/issues/6520). Use the URI module distributed with Ruby: require ‘uri’ if url =~ URI::regexp # Correct URL end Like Alexander Günther said in the … Read more

How do I run a rake task from Capistrano?

A little bit more explicit, in your \config\deploy.rb, add outside any task or namespace: namespace :rake do desc “Run a task on a remote server.” # run like: cap staging rake:invoke task=a_certain_task task :invoke do run(“cd #{deploy_to}/current; /usr/bin/env rake #{ENV[‘task’]} RAILS_ENV=#{rails_env}”) end end Then, from /rails_root/, you can run: cap staging rake:invoke task=rebuild_table_abc

How can I have ruby logger log output to stdout as well as file?

You can write a pseudo IO class that will write to multiple IO objects. Something like: class MultiIO def initialize(*targets) @targets = targets end def write(*args) @targets.each {|t| t.write(*args)} end def close @targets.each(&:close) end end Then set that as your log file: log_file = File.open(“log/debug.log”, “a”) Logger.new MultiIO.new(STDOUT, log_file) Every time Logger calls puts on … Read more

What does send() do in Ruby?

send sends a message to an object instance and its ancestors in class hierarchy until some method reacts (because its name matches the first argument). Practically speaking, those lines are equivalent: 1.send ‘+’, 2 1.+(2) 1 + 2 Note that send bypasses visibility checks, so that you can call private methods, too (useful for unit … Read more

How to create a file in Ruby

Use: File.open(“out.txt”, [your-option-string]) {|f| f.write(“write your stuff here”) } where your options are: r – Read only. The file must exist. w – Create an empty file for writing. a – Append to a file.The file is created if it does not exist. r+ – Open a file for update both reading and writing. The … Read more