Calculate prime numbers

Tried simple Sieve of Eratosthenes in Ruby …

class MyPrime

  attr_reader :primes # there we can read then

  # compute prime numbers up to limit, default is 20
  def initialize(limit = 20)
    @primes = []
    limit = limit.to_i 
    return if limit.to_i < 2
    arr = Hash[*((2..limit).to_a*2).sort] # we can use .zip too
    (2..Math.sqrt(limit)).each do |i|
      next unless arr[i] # already removed
      (i*i..limit).step(i).each{|k| arr.delete(k)}
    end
    @primes = arr.keys.sort # return just keys
  end
end

we can add some tests

require 'test/unit'
require 'my_prime'

class TestMyPrime < Test::Unit::TestCase

  def test_20_primes
    primes = MyPrime.new(20)
    assert_equal [2, 3, 5, 7, 11, 13, 17, 19], primes.primes
  end

  def test_wo_param
    primes = MyPrime.new
    assert_equal [2, 3, 5, 7, 11, 13, 17, 19], primes.primes
  end

  def test_less_than_2
    primes = MyPrime.new(1)
    assert_equal [], primes.primes 
  end

  def test_limit_eq_2
    primes = MyPrime.new(2)
    assert_equal [2], primes.primes
  end

  def test_limit_is_string
    primes = MyPrime.new('20')
    assert_equal [2, 3, 5, 7, 11, 13, 17, 19], primes.primes
  end

  def test_limit_is_float
    primes = MyPrime.new(20.50)
    assert_equal [2, 3, 5, 7, 11, 13, 17, 19], primes.primes
  end

end

fetch all youtube links from any page

We made a list of great youtube videos on facebook comments and wanted to fetch these as a list, so I’ve been thinking how to achieve it. And there’s some javascript code you can paste into your console (javascript consone in a browser), it’ll fetch and display all the links for youtube. Easily change regexp to match url your want.

var seznam = ''; Array.prototype.slice.call(document.getElementsByTagName('a')).forEach(function(i){ if (i.href.match(/^http:\/\/www.youtube.com/) != null) {seznam+=i+"\n";}});document.getElementsByTagName('body')[0].innerHTML="<pre>"+seznam+"</pre>";

cucumber + yajl troubles (OSX Lion)

using rails 3.0.1 and cucumber-rails (~>1.1.0).. and got this weird error message:

dyld: lazy symbol binding failed: Symbol not found: _yajl_set_static_value
  Referenced from: ~/.rvm/gems/ruby-1.9.3-p0/gems/yajl-ruby-1.0.0/lib/yajl/yajl.bundle
  Expected in: flat namespace

dyld: Symbol not found: _yajl_set_static_value
  Referenced from: ~/.rvm/gems/ruby-1.9.3-p0/gems/yajl-ruby-1.0.0/lib/yajl/yajl.bundle
  Expected in: flat namespace

Trace/BPT trap: 5

so.. working solution is:

  • go to the gem itself ~/.rvm/gems/ruby-1.9.3-p0/gems/yajl-ruby-1.0.0/ext/yajl open yajl_ext.h  and yajl_ext.c  and change inline void to static void
  • gmake clean all
  • overwrite yajl.bundle in lib/
example of edited yajl.h
static void yajl_check_and_fire_callback(void * ctx);
static void yajl_set_static_value(void * ctx, VALUE val);
voila! :)