Flowdock

Notes posted to Ruby

RSS feed
March 19, 2015
0 thanks

enumerator and number of lines to read

Example

File.foreach(filename)
  .take(number_of_lines)
  .map do |line|
    # ... stuff ... 
end
March 11, 2015 - (v1_9_3_392)
0 thanks

equals a.fetch and a.at(1)

a.fetch(1) == a.at(1) #=> true

March 1, 2015
0 thanks

Not exactly like map {}.flatten

To clarify on the last comment, conceptually it’s the same, but #flat_map will perform better because there is no need to create an intermediate Array

February 24, 2015
0 thanks

clarification of inputs

split(p1 = v1, p2 = v2)”

in reading the rest of the documentation, i found “p1” and “p2” to be confusing.

I think it should be:

split( pattern, limit )

February 12, 2015
0 thanks

Example is a Bug!

Why is the example showing the use of the #detect method and not #find? Boggles the mind!

January 28, 2015 - (v1_8_6_287 - v1_9_3_392)
0 thanks

Feature

A default pretty printing method for general objects. It calls pretty_print_instance_variables to list instance variables.

If self has a customized (redefined) inspect method, the result of self.inspect is used but it obviously has no line break hints.

This module provides predefined pretty_print methods for some of the most commonly used built-in classes for convenience.

December 9, 2014
0 thanks

See also ConditionVariable

If you need to and processing with respect to a particular resource between 2 or more threads in more complicated ways, it is likely that ConditionVariable is what you’re looking for.

November 17, 2014
0 thanks

Elements need to be in same order

Note that even if the arrays have the same content, the elements need to be ordered:

Example:

x = [1, 2, 3]
y = [3, 2, 1]
z = [1, 2, 3]

x.eql?(y) #=> false
x.eql?(z) #=> true
x.eql?(y.sort) #=> true
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.