Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Tuesday, June 19, 2007

widont.rb

I don't mean to knock Shaun Inman and his wordpress plugin Widon't. It's a very useful plugin that eliminates typographical widows by replacing the last space with a non-breaking space. He says the regular expression is '|([^s])s+([^s]+)s*$|'. This is of course, completely false; something was lost in translation here.

First, the pipe characters are weird but I think PHP accepts them. I've always used the forward slash to denote a regular expression. Second, the s is meant to be \s the notation for whitespace of any sort.

The actual plugin works fine. I think Shaun's just made a typo on his blog.

Here's a similar piece of code in Ruby:

"Lorem Ipsum Dalor Est".gsub(/([^\s])\s+([^\s]+)$/, '\1 \2')
# => "Lorem Ipsum Dalor Est"

I love how Ruby (and Javascript, if I recall correctly) gives regular expressions special status like how most modern languages treat strings. In web development and command line scripting, strings are the only real input/output you work with and regular expressions are akin to the hand of God.

Saturday, May 26, 2007

HashToAttributes.rb

# When this class is initialized, it takes in a Hash and uses the key/value
# pairs to create instance variables. The problem here is that each key needs to
# be verified to make sure it conforms to the naming rules.
#
# This is like converting a Hash to an object (a Hash.to_o method, if you will).
# Great for when you're hacking up a script to parse some text/XML/YAML as a
# once-off. I wouldn't recommend this be used in a production environment.
# 
class HashToAttributes
  attr_reader :attr1, :attr2, :attr3
  attr_writer :attr3
  
  def initialize(hash)
    # Each key becomes an instance variable
    # TODO: check that key conforms to naming rules
    hash.each do |key, value|
      instance_variable_set(("@" + key).to_sym, value);
    end
  end
end

hsh = { 'attr1' => "Oh Vey", 'attr2' => "Virtua Cop 2", 'attr3' => true }
obj = HashToAttributes.new(hsh)
puts obj.attr1       # => "Oh Vey"
puts obj.attr2       # => "Virtua Cop 2"
obj.attr3 = false
puts obj.attr3       # => false

irb-loop.rb

irb(main):001:0> # I guess this is as wide as it goes
irb(main):002:0* 80.times do |i|
irb(main):003:1*   print i % 10
irb(main):004:1>   print "\n" if i == 79
irb(main):005:1> end
01234567890123456789012345678901234567890123456789012345678901234567890123456789
=> 80
irb(main):006:0>

helloworld.rb

# This is as much as you need to know about a programming language.
# The rest will simply fall into place.
puts "Hello World"