A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Ruby basics


Save URL to a file

require 'open-uri'
open('image.png', 'wb') do |file|
    file << open('http://example.com/image.png').read
end

is this the same as:

require 'open-uri'
file = open('image.png', 'wb')
file << open('http://example.com/image.png').read

Fetch URL through a proxy

print Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user, proxy_pass).get URI.parse('http://www.compufer.com/')

Hello world

puts "Hello, what's your name?"
STDOUT.flush
name = gets.chomp
puts 'Hello, ' + name + '.'

Blocks


def try  
  if block_given?  
    yield  
  else  
    puts "no block"  
  end  
end  
try # => "no block"  
try { puts "hello" } # => "hello"  
try do puts "hello" end # => "hello" 

Notes

  • Whichever variables(s) you pass into the block, the method will fill them with something, depending on what its function is. e.g. "open" puts a file handle in there.
  • List of file modes
  • HashHashes
  • ---------------
  • Builder tut1tut2tut3