cat numbers | ruby -e 'puts ARGF.collect {|l| l.match(/^ *(\d+)/)[1].to_i}.inject(0, &:+)'This uses the Ruby 1.9 ARGF feature and matches just the first number listed (possibly preceded by spaces), converts them to an array of integers, then sums them using Array#inject.
Thursday, April 12, 2012
Command one liners
I was fooling with some data using cut, sed, etc. When I needed to sum up all of the numbers, I used to do this with a Perl script (years ago), but it's a one liner in Ruby now:
Friday, December 30, 2011
RVM and CRON with ruby PADRINO
When cron runs a job, the job has very little environment. In my installation, I use RVM to switch between different versions of ruby, and so trying to run any sort of cron job is difficult.
My recommendation is that you start out using a shell script which executes your ruby process. Here's one that works for me:
#!/bin/sh
. /usr/bin/rvm > /dev/null
rvm use ruby-1.9.3-p0
cd /wherever
export PADRINO_ENV=production
/usr/bin/time ./import-noc-events.rb
exit 0
Friday, June 11, 2010
cattr_accessor
When I was new to ruby and rails, I ran into cattr_accessor and it's lack of documentation.
Simply, cattr_accessor creates a class-level accessor for a class variable. It also adds an instance method for accessing the class variable. There are several options that can be specified to remove the instance_reader and instance_writer. Cattr_accessor is located in the file activesupport/lib/active_support/core_ext/class/attribute_accessors.rb.
These class variables are shared with any subclasses, so be carefull. For example -
Loading development environment (Rails 3.0.0.beta3)irb(main):001:0> class Pet irb(main):002:1> cattr_accessor :numberirb(main):003:1> end=> [:number]irb(main):004:0> class Dog <>irb(main):005:1> end=> nilirb(main):006:0> class Cat <>irb(main):007:1> end=> nilirb(main):008:0> Dog.class_eval('number = 4')=> 4irb(main):009:0> Cat.class_eval('number = 0')=> 0irb(main):010:0> puts Dog.class_eval('number')0=> nilirb(main):011:0>
This is because the inherited accessors all reference the Pet's number.
Subscribe to:
Posts (Atom)