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

Jump to

Quick reference

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

Ruby debugging gems

A list of debugger add-ons for ruby:
  • debug (old, built-in)
    • ruby -rdebug foo.rb
    • # works
    • # but can't view code around current line automatically like Perl's  {{v
  • pry (no step-through)
    • require 'pry' # at the top
    • binding.pry # in code to define a breakpoint
    • ruby foo.rb
  • pry with step through:
  • pry-byebug (requires ruby >= 2.2.0)

Ruby iterator cheat sheet

A list of many useful iterators in Ruby for hashes and arrays:
  • each - Do block for each item. Works on hash or array. Can use 'break'. Return nothing.
    • each_index - Same as each but pass in the index to the block
  • collect (aka map) - Do block for each item. Return array. Same as Perl map.
    • collect! / map! - Same as map, but modify array in place
  • select (aka find_all) - Do block for each item. Return array if block is true. Same as Perl grep.
    • select! (aka keep_if) - Same as select but modify array in place
    • reject - Opposite of select. Return if block is false.
    • reject! (aka delete_if) - Same as reject but modify array in place
  • inject(xyzzy) (aka reduce) - Do block for each pair of items, starting with xyzzy & first item.
  • compact - Return array with nil items removed
    • compact! - Same as collect but modify array in place
  • delete(foo) - Remove all items that are equal to foo
  • clear - Remove all items
  • empty? - Return true if array has no items
  • count - Return number of items
  • length (aka size) - Return number of items
  • flatten! - Modify array to be 1-dimensional
  • shuffle! - Shuffle in place
  • sort! - Sort in place
  • bsearch - Find item using binary search
  • combination(3) - Return all combainations of length 3
  • permutation(4) - Return all permutations of length 4
  • sort_by! - Sort in place using keys in block
  • transpose - swap rows and columns
  • zip - step through two arrays at the same time


(sourcesource, source)

Detailed Ruby notes

A list of somewhat advanced Ruby topics:
  • Scope of constants, and namespace: link, link.
  • Keyword arguments: link.

How to install ruby, rake, rubygems

https://www.ruby-lang.org/en/documentation/installation/

For ruby, tried:
  • https://rvm.io/ - wouldn't work on my Suse setup
  • https://github.com/sstephenson/rbenv#readme - worked on Suse. Promising, I like.
    • https://github.com/sstephenson/ruby-build#readme - doesn't work


For rubygems, tried:
  • https://rubygems.org/pages/download - worked

For rake:

  • It comes with ruby


Now learn Ruby:
https://github.com/neo/ruby_koans


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

Install ruby gems

sudo yum -y install gcc ruby-devel rubygems
sudo gem install nokogiri

Parse HTML with Ruby and Nokogiri


doc = Nokogiri::HTML(open(filename, 'r'))
puts doc.xpath('//title')[0].inner_html
puts doc.xpath('//h2')

Ruby: Read+write to database


require 'sqlite3'

db = SQLite3::Database.new( "db1" )
db.execute('INSERT INTO table_name (id, text) VALUES (1, "hello")')
db.execute( "SELECT* FROM table_name" ) do |row|
    puts row.inspect
end

Web scraping with Ruby

In order of goodness:

  • Nokogiri
  • Hpricot
  • Scrapi

Misc Ruby stuff

  • Write to a file:
  • File.open(local_filename, 'w') {|f| f.write(doc) }
  • Read from a file:
  • File.open(local_filename, 'w') {|f| f.write(doc) }
  • stringify: .inspect