Categories
jekyll ruby

Jekyll on Windows

There are already guide out there to get Jekyll installed on Windows machine.

I have problem to start it after installation though, a long list of errors follow,

D:\ruby_projects\olla\jekyll serve
Configuration file: D:/ruby_projects/olla/_config.yml
Source: D:/ruby_projects/olla
Destination: D:/ruby_projects/olla/_site
Generating... Liquid Exception: cannot load such file -- yajl/2.0/yajl in _posts/2013-10-22-welcome-to-jekyll.markdown

And of course, solution is out there as well https://github.com/brianmario/yajl-ruby/issues/116, make sure to read till the very end of the thread. Pre-compiled gem is not Ruby 2.0 compatible, if there is already x86-mingw32 version of yajl installed, make sure to uninstall it then follow these steps

D:\ruby_projects\olla>gem install yajl-ruby --platform=ruby      
Fetching: yajl-ruby-1.1.0.gem (100%)                             
Temporarily enhancing PATH to include DevKit...                  
Building native extensions.  This could take a while...          
Successfully installed yajl-ruby-1.1.0                           
Parsing documentation for yajl-ruby-1.1.0                        
Installing ri documentation for yajl-ruby-1.1.0                  
Done installing documentation for yajl-ruby after 2 seconds      
1 gem installed

If one decided to do development works in a windows machine, by faith you have to jumped over lot of hoops to make thing happen. Latest pygments gem just refuse to work

D:\ruby_projects\olla\jekyll serve                                                                                                 
Configuration file: D:/ruby_projects/olla/_config.yml                                                                              
            Source: D:/ruby_projects/olla                                                                                          
       Destination: D:/ruby_projects/olla/_site                                                                                    
      Generating... C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/posix-spawn-0.3.6/lib/posix/spawn.rb:162: warning: cannot 
  Liquid Exception: No such file or directory - /bin/sh in _posts/2013-10-22-welcome-to-jekyll.markdown

A little search show the solution in StackOverflow, just uninstall the latest pygments gem, and install version 0.5.0 as suggested. Tada, you can jekyll serve and point to localhost:4000 finally.

Now compare all those steps with this one
jekyll_quick_start

Can’t help but feel like developing in Windows environment waaaay more fascinating. Ha.

Categories
ruby ruby on rails

Testing in Sublime

Following railstutorial again, to strengthen my rails basic and pick up new shiny things in rails 4.

Getting sublime to run test directly is quite awesome, I mean you just need to highlight part of the test you wish to run, cmd + shift + R, boom you got your test result, all without needing to leave the comfort of sublime. Sweet.

On the next day though, suddenly it refuse to run, complaining

/bin/sh: rspec: command not found

Stackoverflow answer here go for this one. But a simpler solution below work for me, just go to ~/.config/sublime-text-2/Packages/RubyTest/RubyTest.sublime-settings file and set configuration option “check_for_rvm” to true and you have your mojo back.

test_in_sublime

Categories
python ruby

Trick that work in irb and python shell

This irb tip is from Natasha the Robot. Often we forgot to assign an expression to a variable, you could of course use up arrow to retrieve last command and then move all the way to the front, add a variable and equal sign to it, but that is a lot of troubles.

An easy way is just assign a variable to underscore, like this

text = _

Then you have your previous expression assigned to a variable called text. Magical.

What is more surprising is that just found out that this magical trick works the same in python shell! Even more magical.

Categories
ruby

why attr_accessor

I keep bump into this problem, where I pick up some basic long ago, after a while, get too used to it and forgot the reason why something is done in a particular way.

If I have written about it, then I have a better understanding and longer memory. Like the collection_select method which I drawn a illustration and post about it sometimes ago, it stuck in my memory till now.

This idea is not really new, you learn by teaching, or at least write or blog about it. All that help to clarify your thought.

And so, to help me internalized the reason behind attr_accessor, I quickly googled and read thru this from stackoverflow, yet, am gonna write about it as a process of internalization. Ha.

You keep writing attr_accessor, one day you totally forgot why we did attr_accessor at the first place. Why attr_accessor?

class Human
  def name=(str)
    @name = str
  end
 
  def name
    @name
  end
end

You do that to assign variable to a value, then call the value. This is common repetitive task. Programming is all about eliminating repetitive tasks. So you can do this in ruby

class Human
  attr_reader :name
  attr_writer :name
end

where attr_reader replace name method part, and attr_writer replace the name=(str) method. Still, often attr_writer and attr_reader often come in pair, why not just do it in one step.

class Human
  attr_accessor :name
end

I created a diagram hopefully could better illustrate this in one glance.

Evolution of attr_accessor
Evolution of attr_accessor

That is it. Already felt that now this tie deeper into my memory.

Categories
ruby

require file from same directory in ruby

Requiring a file sitting in the same directory wouldn’t work with this

require 'something'

Seems like Ruby 1.9 remove current directory from load path as I read from Stackoverflow

To make it work you could

require './something'

or use require_relative,

require_relative 'something'

The thing is,

load 'something.rb'

still work. So does that mean load and require have different load path?

Categories
ruby

Regex hammer time

When you have a hammer, you see everything as nails.
A very true message from Dive into Python 3,

Regular expressions are extremely powerful, but they are not the correct solution for every problem. You should learn enough about them to know when they are appropriate, when they will solve your problems, and when they will cause more problems than they solve.

But it is easy to fall into the trap of using regex for everything.
I need to find the last string from a path, where

path = "d:/some/directory-with dash-and space"

So here is how I try to get the last string in a path, with regex

path.match(/\w*$/)

trying to capture any word characters at the end of the string with \w*$, but only captured the last word “space”, not good.

path.match(/(\s|\w)*$/)[0]

to match either whitespace (\s) or word characters (\w) at the end of the string, the result is “and space”, dashed is not captured, not good.

path.match(/[^\/]*$/)

[^\/] to take in everything except “/”, result is “directory-with dash-and space”, it works!

Only later I found out there is a really simple way to do this

File.basename(path)

will actually give you “directory-with dash-and space”. Plus, it will ignore ending slash if there is any.
Duh!

Categories
ruby

ruby tonic

This should taste good.

 

Categories
ruby

RubyMonk

Finally. Thank you master.

Categories
ruby

bubble sort

Understanding sorting algorithm by just reading text or still illustration takes a lot of mind gymnastic. Apparently, there are lot of videos online, trying to explain the concept. But not all explain it as good though, some with really boring animation, some with crappy background music, and some even both . Here are two that I find did a great job in explaining bubble sort,

This one from codegearguru. Instead of creating graphic, or cutting out paper to represent data in the sorting process, just use the poker cards! That seems obvious now, but I didn’t think about it when I try to illustrate sorting to myself initially. Ha. Think there is a series of video created for different type of sorting algorithm as well, so definitely a great tool to understand sorting algorithm. Bonus near the end of the video, another technique called shaker sort or cocktail sort is also explained, which is basically a bidirectional bubble sort which should speed up the sorting speed.

Another one from Miles Hauskaz, just plain simple and succinct explanation and a video nicely done as well.

Sorting Algorithms – Bubble Sort from Miles Hauskaz on Vimeo.

So, this is my implementation of bubble sort, admittedly not the best that you can find, but that will do for me now, until I have time to come back and do some refactoring.

arr = %w{g a c b j e e}
i = arr.length - 1
count = 0
n = arr.length - 1
def swap(m,n) 
  arr = []
  if m > n
    arr << n
	arr << m
  else
    arr << m
	arr << n   end end while n > 0
  while count < i
    puts "comparing #{arr[count]} to #{arr[count+1]}"
    a = swap(arr[count],arr[count+1])
    arr[count..count+1] = a
    count += 1
  end
  n -= 1
  i -= 1
  count = 0
end
p arr
Categories
ruby

map and each

It is a bit difficult for me to understand the difference between map and each, until I found out this in irb accidentally,

irb(main):001:0> name = %w{guido knuth adrian dhh pg}
=> ["guido", "knuth", "adrian", "dhh", "pg"]
irb(main):002:0> name.each {|n| n.upcase}
=> ["guido", "knuth", "adrian", "dhh", "pg"]
irb(main):003:0> name.map {|n| n.upcase}
=> ["GUIDO", "KNUTH", "ADRIAN", "DHH", "PG"]

map and each are suppose to do almost the same thing, but why each didn’t return the correct result in uppercase like what map did?

The different is each yield each element in the collection to the code block, in this case perform the upcase method, but return the receiver, which is the original array, hence an array of lower case names.

Whereas, map return a new array, consists of elements already went through the code block, hence an array of upper case names.

irb(main):007:0> name.each {|n| p n.upcase}
"GUIDO"
"KNUTH"
"ADRIAN"
"DHH"
"PG"
=> ["guido", "knuth", "adrian", "dhh", "pg"]
irb(main):006:0> name.map {|n| p n.upcase}
"GUIDO"
"KNUTH"
"ADRIAN"
"DHH"
"PG"
=> [nil, nil, nil, nil, nil]

So here you can see with p, both map and each output the uppercase names, but look more carefully, the return value of each, as expected, is the original array. map however, return an array of nils!

Why is that?