Flowdock

Notes posted to Ruby

RSS feed
March 19, 2014 - (v1_8_6_287 - v1_9_3_392)
1 thank

Right Partitioning Filename extension

1.9.3p392 :013 > x = “picture.2.jpg”

=> "picture.2.jpg" 

1.9.3p392 :015 > x.rpartition(‘.’)

=> ["picture.2", ".", "jpg"] 
February 19, 2014
0 thanks

Undocumented pile of ruby

> If you’d like to read someone’s RSS feed with your Ruby code, you’ve come to the right place


No, you’ve definitely come to wrong place. RSS is one of the worst documented libraries I’ve ever seen for Ruby. It’s as confusing and misleading as it can get.

February 4, 2014 - (v1_9_3_392)
0 thanks

Alternative to :symbol

You can also pass string as an alternative to :symbol

k = Klass.new

k.send “hello”, “gentle”, “readers” #=> “Hello gentle readers”

January 22, 2014
0 thanks

re: question?

Nope. Read it again:

> This generates a sequence of self.size n-element arrays

If any of the arguments are longer than the receiver, the elements beyond the receiver’s length are ignored

November 19, 2013
0 thanks

Return value not correct

It seems like trap returns nil if the handler was “DEFAULT”, but calling trap with nil causes a “IGNORE”

2.0.0-p247 :020 > p trap("CHLD", "DEFAULT")
nil
 => nil 
2.0.0-p247 :021 > p trap("CHLD", nil)
nil
 => nil 

So it seems that once you trap a signal, there isn’t a way to reset them back to what they were originally.

November 15, 2013
0 thanks

Test if an array is included in another

a note for anoiaque solution…

before running you need to require set

require 'set'
class Array
  def included_in? array
    array.to_set.superset(self.to_set)
  end
end

[1,2,4].included_in?([1,10,2,34,4]) #=> true
November 12, 2013
0 thanks

Be aware

Be aware

'John    Doe №88'.sqeeze 
=> 'John Doe №8' # with just one '8'
September 27, 2013
0 thanks

Using find_index to return first match. Profit!

This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.

Code example

class Widget < Struct.new(:name, :profit); end

class WidgetManager
  def initialize(*widgets)
    @widgets = widgets
  end
  def is_any_widget_profitable?
    @widgets.find_index { |w| w.profit > 0 }  # <== usage!
  end
end

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', 200), Widget.new('c', 300))
wm.is_any_widget_profitable?  # => 1
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "some profit"

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', -200), Widget.new('c', -300))
wm.is_any_widget_profitable?  # => nil
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "all loss"
September 25, 2013
0 thanks

Anothery way

This Worked For Me

require File.expand_path('../app/models/extenstions/active_record_ext', File.dirname(__FILE__))

I did this in application.rb

September 9, 2013
1 thank

Using reject to remove key/value pairs from a hash

Code example

# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |k,v| v.empty? } #=> {:a=>"first", :c=>"third"}

# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? } # => {:a=>"first", :c=>"third"}

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } # => {:c=>"third"}
May 16, 2013
0 thanks

Bug in Ruby or this documentation

%Q doesn’t return microseconds but milliseconds! Use %s%6N for microseconds.

May 16, 2013
1 thank

Bug in Ruby or this documentation

%Q doesn’t return microseconds but milliseconds! Use %s%6N for microseconds.

April 17, 2013
0 thanks

@UnfalseIdeas

What is the purpose of

Hash[one: 1, two: 1]

When you can write

{one: 1, two: 2}

Aren’t you just passing a hash into the [] method?

April 4, 2013
0 thanks

HTTPS request

Hey, guys!

You have one mistake in example code.

uri = URI('https://secure.example.com/some_path?query=string')

Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https').start do |http|
  request = Net::HTTP::Get.new uri.request_uri

  response = http.request request
end

Here HTTP::start method called twice. This code should look like

Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https') do |http|
  request = Net::HTTP::Get.new uri.request_uri

  response = http.request request
end

It’s work - I checked.

April 2, 2013 - (v1_8_6_287 - v1_9_3_392)
0 thanks

Passing in an Array instead of individual arguments

Pass in array instead of list

h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }

keys_i_want = %w(cow cat)

h.values_at(*keys_i_want) #=> ["bovine", "feline"]
April 2, 2013 - (v1_9_3_392)
0 thanks

output GBK

‘I am 中国人’.encode(‘gbk’,‘utf-8’)

April 2, 2013
0 thanks

you need kconv

require ‘kconv’

then

“中国人民很行”.toutf8

March 13, 2013
1 thank

Another Hash#without

Mange made me think, and I wanted to expand on his example with a small change.

class Hash
  def without(*keys)
    dup.without!(*keys)
  end

  def without!(*keys)
    reject! { |key| keys.include?(key) }
  end
end

h = { :a => 1, :b => 2, :c => 3 }
h.without(:a)      #=> { :b => 2, :c => 3 }
h #=> { :a => 1, :b => 2, :c => 3 }  

h.without(:a, :c)  #=> { :b => 2 }

h.without!(:a, :c) # { :b => 2 }
h #=> { :b => 2 }
March 5, 2013
0 thanks

Minor correction to Rubybull's examples?

Was your first example intended to be:

a=[11,22,31,224,44]
=> [11, 22, 31, 224, 44]
a.each.with_index { |val,index| puts "index: #{index} for #{val}" }
February 25, 2013 - (v1_9_3_125)
0 thanks

Using the undef/replace param overwrites the fallback parameter

If you want to provide a fallback Hash / Proc / Object you must not define the :undef and/or replace params since they overwrite the fallback.

How fallback works

fallback = Hash.new { '?' }
fallback["\u2014"] = "-"
"\u2014".encode!("ISO-8859-15", fallback: fallback)
=> "-"

Undef overwrites fallback:

fallback = Hash.new { '?' }
fallback["\u2014"] = "-"
"\u2014".encode!("ISO-8859-15", fallback: fallback, undef: :replace, replace: '?' )
=> "?"
February 25, 2013
0 thanks

Where did this go?

For Ruby 1.9 and later, use Kernel#Array to get this functionality.

February 23, 2013
0 thanks

Modes listed in IO class

See class IO for file open modes

February 20, 2013
0 thanks

Freezing Time.now

You’d be much better off using the Timecop gem ( rubygems.org/gems/timecop ) than than manually writing monkey-patches to freeze Time.now etc.

It also supports time travel (i.e. changing the time, but allowing the clock to continue running).

February 3, 2013 - (v1_9_3_125)
0 thanks

How does enum#each_index differ from enum#with_each_index ?

Here is the working one each_with__index:

a=[11,22,31,224,44].each_with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
  index: 0 for 11
  index: 1 for 22
  => [11, 22, 31, 224, 44]

Below couldn’t produce the output, as with_index couldn’t work on the array.To make it workble, we need to first convert it to enumerator. And that can be done via the help of .to_enum, .each, or .map

a = [11,22,31,224,44].with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
=>NoMethodError: undefined method `with_index' for [11, 22, 31, 224, 44]:Array
       from (irb):2
       from C:/Ruby193/bin/irb:12:in `<main>'

Here is the working one with_index:

a = [11,22,31,224,44].each.with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
index: 0 for 11
index: 1 for 22
=> [11, 22, 31, 224, 44]
February 3, 2013 - (v1_9_3_125)
0 thanks

Difference between enum#with_object and enum#each_with_object

I found a very good post on SO - which clearly explained the difference between enum#with_object and enum#each_with_object. The link is as follows:

http://stackoverflow.com/questions/14671881/how-does-enumwith-object-differ-from-enumeach-with-object/14672305#14672305

February 2, 2013 - (v1_9_3_125)
1 thank

Enumerator#with_index has confusing documentation

Enumerator#with_index has confusing documentation, but hopefully this will make it clearer.

Code example

a=[11,22,31,224,44].to_enum
=> [11, 22, 31, 224, 44]
a.with_index { |val,index| puts "index: #{index} for #{val}" }
index: 0 for 11
index: 1 for 22
index: 2 for 31
index: 3 for 224
index: 4 for 44

a=[11,22,31,224,44].to_enum
=> #<Enumerator: [11, 22, 31, 224, 44]:each>
a.with_index(2){ |val,index| puts "index: #{index} for #{val}" if val > 30 }
index: 4 for 31
index: 5 for 224
index: 6 for 44
=> [11, 22, 31, 224, 44
January 14, 2013 - (>= v1_8_6_287)
0 thanks

Pass a block

While this example is not so obvious on first look what the block passed does, here’s a small explanation:

when the block is passed to this function, the uniqueness is checked based on a value returned by that block.

For example if it’s array of objects with “user_id” method, then this would be:

tasks.uniq{|t| t.user_id } # returns only tasks with unique user_id 
January 13, 2013
0 thanks

Note sure if doco is correct

(Note this was an issue in Ruby 1.9.2, 1.9.3 has been corrected, not sure why the generated doc is still incorrect)

Both exist? and exists? use the same underlying C function

file.c, line 5444

define_filetest_function("exist?", rb_file_exist_p, 1);
define_filetest_function("exists?", rb_file_exist_p, 1);

rb_file_exist_p does an rb_stat call, and just checks for no error.

rb_stat returns the result of a call to fstat, if the passed in value is a IO object, or stat (or your platforms equivalent). Both these return 0 on success, -1 on failure.

So both really just check that the underlying “thing” can respond to “stat” correctly. There are many things in a unix-style filesystem that have a “file” structure, not just traditional files. These functions help when you don’t care what type an entry is, just that it exists.

There doesn’t seem to be any difference in the two methods

File.directory? can test if a named file is a dir

December 10, 2012
0 thanks

@drewyoung1

Including module in a class does not automatically over-write methods defined with the same name.

Ex:

module Mod

def exit(code = 0)
  puts "Exiting with code #{code}"
  super
end

end

class OriginalClass

include Mod
def exit
  puts "Original message"
end

end

OriginalClass.new.exit 99

Produces:

exit': wrong number of arguments (1 for 0) (ArgumentError)

if you use this construct, the alias_method will work similar to super:

module Mod

alias_method :super_exit, :exit
def self.included base
  base.instance_eval do
    def exit(code = 0)
      puts "Exiting with code #{code}"
      super_exit
    end
  end
end

end