Posts Tagged by Ruby
refactoring in Go – rather pleasant actually…
| 12-Feb-2013 | Posted by Sonia Hamilton under Golang, Perl, Python, Ruby, Vim |
I’ve just finished refactoring a large Go program, and the process was rather…. pleasant.
Static typing catches all those obscure errors I wouldn’t think about in a scripting language (Python, Perl, Ruby, etc). My process is:
- type :make in vim (I have a dummy Makefile in my Go project just for vim)
- vim jumps cursor to error (vim quickfix list)
- “oh, I shouldn’t do that” – fix (type type type)
- start again
Finish rather sooner than expected, run tests, smile in knowledge program is working properly.
Update
To quickly setup the make command for Go, type this in a Vim window:
:setlocal makeprg=go\ build\ \.
Or even better configure vim via your ~/.vimrc, for example:
autocmd BufRead *_test.go setlocal makeprg=go\ test\ \. autocmd BufRead *.go setlocal makeprg=go\ test\ \./..
Thanks Martin for the comment!
Learning Clojure – my books
| 11-May-2012 | Posted by Sonia Hamilton under Clojure, Lisp, Ruby |
I’ve been playing with Lisp and now Clojure for a couple of years now. Here’s a list of the books I’ve read on my journey to Clojure enlightenment (I’ve still got a long way to go…).

My first Clojure book wasn’t even about Clojure, it was about Lisp! One Sunday afternoon I was lurking in the computer section of a local bookshop (a great way to spend a Sunday afternoon), and came across Land of Lisp. I’d heard about Lisp, that “obsolete” language that used to be used for Artificial Intelligence but who uses it nowadays? Anyway, the cover was colourful and the cartoons were great, and before I knew it I’d read a couple of chapters and wanted to know about this Lisp stuff and I bought the book.

But after reading it for a while and getting sidetracked by Scheme and the greatest book every written about programming, Land of Lisp languished on my bookshelf. The example used in the book (yet another game) didn’t relate to my day-to-day use of programming. I was getting lost because I wasn’t doing any exercises, and Lisp just didn’t seem to be an acceptable Lisp.

Seven Languages in Seven Weeks pointed me towards Erlang, Haskell and Clojure. Ah-hah! Clojure – runs on the JVM (so I can use it machines where I can’t/don’t want to install stuff, just like JRuby). A modern Lisp with cleaned up syntax that has access to all the Java libraries for doing real world stuff. I’m hooked!

At a Ruby on Rails Oceania (RORO) meetup someone was raving about The Joy of Clojure. So I drank from the firehose and my brain exploded and nothing made sense. As Steve Yegge (a fellow Googler) says in the intro, “you’ll learn fast” – but only if you’re already comfortable with Lisp. The book moves too fast, the explanations are cryptic, and it seems to bounce all over the place. Another book to languish on my book shelf.

My next book Practical Clojure was where things started to make sense. It’s more directed at beginners and just explains how the language works. But it’s a thin book (not enough detail) and some sections just seem to be reprints of the API (function foo does this and here’s a 5 line example; function bar does this and here’s a 5 line example). No real digging into the how and why of using Clojure.

And onto my favourite Clojure book – Clojure Programming by Emerick et al. Like many O’Reilly books it’s definitive. Lots of detailed examples, clear explanations, great diagrams, coverage of related areas (eg Clojure for web programming). Example code comparing how you do things in Clojure with other languages (Java, Python, Ruby). This is the book where I’ve really started to understand Clojure.
Now I’m working through the 4clojure problem list (really interesting). Then I’ll probably buy some more books from The Clojure Bookshelf. And continue reading Paul Graham’s On Lisp (I got it printed through Lulu). And one day I’ll reach enlightenment :-)

Ruby, Lisp, Python
| 20-Mar-2012 | Posted by Sonia Hamilton under Lisp, Python, Ruby |
Up late tonight reading about Emacs Lisp, I came across Tour de Babel by Steve Yegge comparing different languages (C, C++, Java, etc), and why he likes Lisp and Ruby so much. I’m stuck in stodgy Python land at the moment, this is balm for the soul:
Anyway, Ruby stole everything good from Perl; … for the most part, Ruby took Perl’s string processing and Unix integration as-is, meaning the syntax is identical, and so right there, before anything else happens, you already have the Best of Perl. And that’s a great start, especially if you don’t take the Rest of Perl.
But then Matz took the best of list processing from Lisp, and the best of OO from Smalltalk and other languages, and the best of iterators from CLU, and pretty much the best of everything from everyone. And he somehow made it all work together so well that you don’t even notice that it has all that stuff.
Ruby, blocks and procs
| 30-Aug-2011 | Posted by Sonia Hamilton under Ruby |
Some notes on ruby, blocks, and procs.
Manually creating blocks
Ruby has three ways of manually creating blocks: Proc.new, lambda, and proc. They have slightly different behaviour, and the behaviour also varies between Ruby 1.8 and 1.9!
- lambda checks that the number of arguments passed matches the number of block parameters
- whereas Proc.new doesn’t check (however the block may raise an error, depending on it’s code)
- and proc behaves like lambda in Ruby 1.8, and like Proc.new in Ruby 1.9. So, avoid using proc!
A bit of code to demonstrate this:
multiplier_l = lambda { |a, b| puts "a * b is: #{a*b}" }
multiplier_p = Proc.new { |a, b| puts "a * b is: #{a*b}" }
multiplier_l.call( 3,4,5 )
ArgumentError: wrong number of arguments (3 for 2)
multiplier_p.call( 3,4,5 )
a * b is: 12
> multiplier_p.call( 1 )
TypeError: nil can't be coerced into Fixnum # in this case, Proc handled one param, but block errored
And now using rvm to switch between Ruby versions:
RUBY_VERSION
=> "1.8.7"
multiplier_p = proc { |a, b| puts "a * b is: #{a*b}" }
multiplier_p.call( 3,4,5 )
ArgumentError: wrong number of arguments (3 for 2)
RUBY_VERSION
=> "1.9.2"
multiplier_p = proc { |a, b| puts "a * b is: #{a*b}" }
multiplier_p.call( 3,4,5 )
a * b is: 12
Scoping
In Ruby 1.8, block parameters can overwrite parameters of the same name in the current scope; in Ruby 1.9 they’re protected.
> hello = "hello"
> def frenchy
> x = "bonjour"
> yield x
> end
> puts hello
hello
> frenchy { |hello| puts hello }
bonjour # as expected
> puts hello
bonjour # ouch! In 1.9 you'd get "hello"
&block
Some of the Rails and Ruby library code define methods with &block as the last parameter to capture an anonymous block.
- anonymous blocks are ignored if they’re not used, and &block is an optional parameter that must appear as the last parameter
- it’s effectively a type-checked parameter – it will only accept an anonymous block or a proc (if proceeded with &)
- the block can be called with call or yield
- you can check if a block was passed using block_given?
- &block is sort of an “invisible parameter” at the end of all methods. But by explicitly using &block, callers get more flexibility when using your method ie they can pass in a proc (perhaps defined elsewhere and used multiple times)
Anonymous blocks are ignored if they’re not used:
> def foo(a)
> puts "a is #{a}"
> end
> foo(1)
a is 1
> foo(1) { puts "2" }
a is 1
Conversely if &block is declared as a parameter, using it is optional:
> def foo(a, &block)
> puts "a is #{a}"
> end
> foo(1)
a is 1
Procs can be called with call; anonymous blocks can be called or yielded to.
> hello = lambda { puts "good bye" } # define a proc for later use
> def foo(a, b, &block)
> puts "a is #{a}"
> b.call # proc with call
> block.call # block with call
> yield # block with yield
> end
> foo(1, hello) { puts "fred" } # with an anonymous block
a is 1
good bye
fred
fred
> foo(1, hello, &hello) # with a proc; notice & syntax
a is 1
good bye
good bye
good bye
You can check if an anonymous block was supplied using block_given?
> def foo(a, &block)
> puts "a is #{a}"
> block.call if block_given?
> yield if block_given?
> end
> foo(1) { puts "mary" }
a is 1
mary
mary
> def foo(a) # or, without defining the block parameter
> puts "a is #{a}"
> yield if block_given? # therefore can only yield not call
> end
&block is sort of an “invisible parameter” at the end of all methods. But by explicitly using &block, callers get more flexibility when using your method:
> def foo(a) # no &block defined in parameters
> puts "a is #{a}"
> yield if block_given?
> end
> foo(1) { puts "john" } # works as expected
a is 1
john
> foo(1, hello)
ArgumentError: wrong number of arguments (2 for 1) # dang! I can't use my super-duper hello proc
Precedence
do .. end has weaker precedence than { }. For example, if foo and bar are both methods:
These are both the same ie the method foo receives two parameters, bar and a block.
foo bar do |s| puts(s) end foo(bar) do |s| puts(s) end
And these are both the same ie foo and bar both receive one parameter; foo the call to bar, and bar a block:
foo bar { |s| puts(s) }
foo( bar { |s| puts(s) } )
Of course the moral of story is not to rely on obscure precedence rules, rather use parentheses whenever something is unclear – as always, in any language.
Closures
Blocks are closures ie they store or carry the value local variables from the the original scope into a different scope. They’re another way of reusing the same logic with slightly different values. For example:
> def build_header( level )
> return lambda { |text| "<#{level}>#{text}</#{level}>" }
> end
> h1 = build_header("h1")
> h1.call("Examples")
<h1>Examples</h1>
> h2 = build_header("h2")
> h2.call("Details")
<h2>Details</h2>
Ruby and Rails – Time, Date, DateTime, TZInfo
| 30-Jun-2011 | Posted by Sonia Hamilton under Ruby, Ruby on Rails |
From a discussion (Ruby – The Non-awesome parts) on the RORO email list – the differences between Time, Date, DateTime and TZInfo:
>> Time vs Date vs DateTime vs TZInfo (vs ActiveSupport::TimeZone). Which
>> do I use and when?
Time is a timestamp and can represent a moment in time no matter where
it occurred in the world, agnostic of timezone. Think UNIX timestamps.
Date is a thing on a calendar that might mean a different moment in
time to different people depending on their timezone. Think of Date
for things like recording your birthday. DateTime subclasses Date and
adds hour, minute, second and timezone information to a Date so it
becomes a lot like Time, but that makes me unsure when to use DateTime
and when to use Time, to be honest.
Time has timezone capabilities built in. TZInfo has a different set of
timezone capabilities and operates with Time objects, but seems to
ignore their built-in timezone settings. I’m still not sure why.
Recent Comments
<<EOF>>was eaten...cat <>~/.vi...