String concatenation in Ruby

You can do that in several ways: As you shown with << but that is not the usual way With string interpolation source = “#{ROOT_DIR}/#{project}/App.config” with + source = “#{ROOT_DIR}/” + project + “/App.config” The second method seems to be more efficient in term of memory/speed from what I’ve seen (not measured though). All three … Read more

Uninstall old versions of Ruby gems

# remove all old versions of the gem gem cleanup rjb # choose which ones you want to remove gem uninstall rjb # remove version 1.1.9 only gem uninstall rjb –version 1.1.9 # remove all versions less than 1.3.4 gem uninstall rjb –version ‘<1.3.4’

Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so: require ‘json’ JSON.parse(json_string) If you’re using an older Ruby, you may need to install the json gem. There are also other implementations of JSON for Ruby that may fit some use-cases better: YAJL C Bindings … Read more

How to map and remove nil values in Ruby

You could use compact: [1, nil, 3, nil, nil].compact => [1, 3] I’d like to remind people that if you’re getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you’ve got code smell and need to rethink your logic. For instance, if you’re … Read more

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here’s the real answer. require ‘date’ Time.at(seconds_since_epoch_integer).to_datetime Brief example (this takes into account the current system timezone): $ date +%s 1318996912 $ irb ruby-1.9.2-p180 :001 > require ‘date’ => true ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> Further update (for UTC): ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime => #<DateTime: 2011-10-19T04:01:52+00:00 … Read more

How to run Rake tasks from within Rake tasks?

If you need the task to behave as a method, how about using an actual method? task :build => [:some_other_tasks] do build end task :build_all do [:debug, :release].each { |t| build t } end def build(type = :debug) # … end If you’d rather stick to rake‘s idioms, here are your possibilities, compiled from past … Read more

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