variable snippets

MySQL rownum equivalent

Tagged mysql, variable, rownum, user  Languages sql

MySQL doesn't have rownum, but user variables can be used as a replacement:

select @rownum:=@rownum+1 'rank', p.* from products p, (SELECT @rownum:=0) r order by created_at desc limit 10;

Read more: MySQL 5.0 Reference Manual

Class variables vs Class instance variables in Ruby

Tagged instance, variable, class, ruby  Languages ruby

Class variables (available to whole inheritance tree) and class instance variables (private to the class) in Ruby can be confusing:

class Foo
  @@cls_var = 'foo'
  @cls_instvar = 'foo'

  def test
    p "instance:"
    p "  class variable: #{@@cls_var}"
    p "  class instance variable: #{@cls_instvar}"
  end

  def self.test
    p "class:"
    p "  class variable: #{@@cls_var}"
    p "  class instance variable: #{@cls_instvar}"
  end
end

class Bar < Foo
  @@cls_var = 'bar'
  @cls_instvar = 'bar'
end

f = Foo.new
p "------------"
p "Foo"
p "------------"
f.test
p "~~~~~~~~~~~~"
Foo.test

p "------------"
p "Bar"
p "------------"
b = Bar.new
b.test
p "~~~~~~~~~~~~"
Bar.test

Output is:

------------
Foo
------------
instance:
    class variable: bar
    class instance variable: 
~~~~~~~~~~~~
class:
    class variable: bar
    class instance variable: foo
------------
Bar
------------
instance:
    class variable: bar
    class instance variable: 
~~~~~~~~~~~~
class:
    class variable: bar
    class instance variable: bar