Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112012-11-18T20:12:53ZRuby Issue Tracking System
Redmine Ruby master - Feature #7384 (Open): Rename #each_with_object to #each_withhttps://bugs.ruby-lang.org/issues/73842012-11-18T20:12:53Ztrans (Thomas Sawyer)
<p>I propose that #each_with_object be renamed to #each_with, for the following reasons:</p>
<ol>
<li>
<p>The original name is too long. When general purpose methods have long names it tends to deter developers from using them even when they are a good fit to the use case.</p>
</li>
<li>
<p>The last word, "object", is completely redundant. All methods that take an argument could say the same thing. e.g. Array#push is not named #push_object though that is obviously what it means.</p>
</li>
<li>
<p>The change need not effect backward compatibility b/c #each_with_object can remain an alias of #each_with for as long as deemed necessary.</p>
</li>
</ol> Ruby master - Feature #7377 (Open): #indetical? as an alias for #equal?https://bugs.ruby-lang.org/issues/73772012-11-17T09:47:45Zaef (Alexander E. Fischer)aef@raxys.net
<p>As my feature request <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: #eql? and #equal? naming (Rejected)" href="https://bugs.ruby-lang.org/issues/7359">#7359</a> got rejected, here a more backward-compatible approach:</p>
<p>In my opinion the difference between #eql? and #equal? is really unintuitive. How about making their difference more obvious by giving one of them a more accurate name?</p>
<p>My proposal is to alias #equal? to #identical?.</p>
<p>I'll write a patch, if this is acceptable.</p> Ruby master - Feature #7362 (Assigned): Adding Pathname#start_with?https://bugs.ruby-lang.org/issues/73622012-11-15T22:38:40Zaef (Alexander E. Fischer)aef@raxys.net
<p>If a Pathname starts with another Pathname, that means that the former Pathname lies below the latter Pathname, as long as both Pathnames are interpreted from the same location or both are given as absolute.</p>
<p>Therefore I would like to see a method #start_with? just like the one on String but for Pathnames.</p>
<p>If you like the idea, just tell me. I will provide a patch then.</p> Ruby master - Feature #7349 (Assigned): Struct#inspect needs more meaningful outputhttps://bugs.ruby-lang.org/issues/73492012-11-14T11:32:05Zpostmodern (Hal Brodigan)postmodern.mod3@gmail.com
<p>When inheriting directly from Struct.new, Class#ancestors shows a meaningless anonymous Class:</p>
<pre><code>class Point < Struct.new(:x, :y)
def distance
((x ** 2) + (y ** 2)) ** 0.5
end
end
Point.ancestors
# => [Point, #<Class:0x007fe204a1a228>, Struct, Enumerable, Object, Kernel, BasicObject]
</code></pre>
<p>Perhaps, the anonymous Class could list the Struct's fields?</p>
<pre><code>#<Class:x, y>
</code></pre> Ruby master - Feature #7341 (Open): Enumerable#associatehttps://bugs.ruby-lang.org/issues/73412012-11-13T08:29:55Znathan.f77 (Nathan Broadbent)nathan.f77@gmail.com
<p>Jeremy Kemper proposed Enumerable#associate during the discussion in <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: map_to alias for each_with_object (Rejected)" href="https://bugs.ruby-lang.org/issues/7297">#7297</a>, with the following details:</p>
<hr>
<p>Some background:</p>
<p><a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Enumerable#categorize (Rejected)" href="https://bugs.ruby-lang.org/issues/4151">#4151</a> proposes an Enumerable#categorize API, but it's complex and hard to understand its behavior at a glance.<br>
<a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: Enumerable#to_h (Closed)" href="https://bugs.ruby-lang.org/issues/7292">#7292</a> proposes an Enumerable#to_h == Hash[...] API, but I don't think of association/pairing as explicit coercion, so #to_h feels misfit.</p>
<p>Associate is a simple verb with unsurprising results. It doesn't introduce ambiguous "map" naming. You associate an enumerable of keys with yielded values.</p>
<p>Some before/after examples:</p>
<p>Before: Hash[ filenames.map { |filename| [ filename, download_url(filename) ]}]<br>
After: filenames.associate { |filename| download_url filename }</p>
<a name="gt-foojpggthttp-"></a>
<h1 >=> {"foo.jpg"=>"http://...", ...}<a href="#gt-foojpggthttp-" class="wiki-anchor">¶</a></h1>
<p>Before: alphabet.each_with_index.each_with_object({}) { |(letter, index), hash| hash[letter] = index }<br>
After: alphabet.each_with_index.associate</p>
<a name="gt-agt0-bgt1-cgt2-dgt3-egt4-fgt5-"></a>
<h1 >=> {"a"=>0, "b"=>1, "c"=>2, "d"=>3, "e"=>4, "f"=>5, ...}<a href="#gt-agt0-bgt1-cgt2-dgt3-egt4-fgt5-" class="wiki-anchor">¶</a></h1>
<p>Before: keys.each_with_object({}) { |k, hash| hash[k] = self[k] } # a simple Hash#slice<br>
After: keys.associate { |key| self[key] }</p>
<hr>
<p>It's worth noting that this would compliment ActiveSupport's Enumerable#index_by method: <a href="http://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by" class="external">http://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by</a><br>
#index_by produces '{ => el, ...}', while #associate would produce '{el => , ...}'.</p>
<p>For cases where you need to control both keys and values, you could use '[1,2,3].map{|i| [i, i * 2] }.associate', or continue to use 'each_with_object({})'.</p> Ruby master - Feature #7340 (Open): 'each_with' or 'into' alias for 'each_with_object'https://bugs.ruby-lang.org/issues/73402012-11-13T08:17:25Znathan.f77 (Nathan Broadbent)nathan.f77@gmail.com
<p>Following on from the discussions at <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: map_to alias for each_with_object (Rejected)" href="https://bugs.ruby-lang.org/issues/7297">#7297</a> and <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Enumerable#to_h proposal (Rejected)" href="https://bugs.ruby-lang.org/issues/7241">#7241</a>, it is apparent that a shorter alias for 'each_with_object' would be much appreciated.</p> Ruby master - Feature #7321 (Assigned): Newton.#nsolve の第 2 引数が複数の役割を持つhttps://bugs.ruby-lang.org/issues/73212012-11-10T16:17:17Zsho-h (Sho Hashimoto)sho-h@netlab.jp
<p>Newton.#nsolve の第 2 引数 x は以下の 2 つの役割を持つようです。</p>
<ul>
<li>探索を開始する点</li>
<li>解を代入</li>
</ul>
<p>newton.rb のコメントにも同じ内容が記述してあるのでわかるといえばわかるのですが、できればそれぞれ分けた方がわかりやすいのではないかと思いました。Newton.#nsolve の戻り値として返すか、引数を追加するのはどうでしょう。</p> Ruby master - Feature #7314 (Assigned): Convert Proc to Lambda doesn't work in MRIhttps://bugs.ruby-lang.org/issues/73142012-11-09T01:30:19Zschneems (Richard Schneeman)
<p>I have code where I need to convert a proc to a lambda (i need to be able to return out of the block). I would expect that passing a proc into a lambda to return a lambda. When I run this code on MRI i do not get the result I would expect</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">my_proc</span> <span class="o">=</span> <span class="nb">proc</span> <span class="p">{</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">}</span>
<span class="n">my_lambda</span> <span class="o">=</span> <span class="nb">lambda</span> <span class="o">&</span><span class="n">my_proc</span>
<span class="n">my_lambda</span><span class="p">.</span><span class="nf">lambda?</span>
</code></pre>
<p>The result is <code>false</code> but I would expect it to be <code>true</code></p>
<p>There is currently a way to turn a proc into a lambda in MRI like this:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">def</span> <span class="nf">convert_to_lambda</span> <span class="o">&</span><span class="n">block</span>
<span class="n">obj</span> <span class="o">=</span> <span class="no">Object</span><span class="p">.</span><span class="nf">new</span>
<span class="n">obj</span><span class="p">.</span><span class="nf">define_singleton_method</span><span class="p">(</span><span class="ss">:_</span><span class="p">,</span> <span class="o">&</span><span class="n">block</span><span class="p">)</span>
<span class="k">return</span> <span class="n">obj</span><span class="p">.</span><span class="nf">method</span><span class="p">(</span><span class="ss">:_</span><span class="p">).</span><span class="nf">to_proc</span>
<span class="k">end</span>
</code></pre>
<p>But this feels like a hack, and is not supported across other implementations. I would expect that passing a proc into a lambda to return a lambda, I believe it is a bug.</p> Ruby master - Feature #7250 (Open): A mechanism to include at once both instance-level and class-...https://bugs.ruby-lang.org/issues/72502012-10-31T18:59:56Zalexeymuranov (Alexey Muranov)
<p>=begin<br>
I have simply commented first on <a class="issue tracker-2 status-7 priority-4 priority-default closed" title="Feature: Inheritable #included/#extended Hooks For Modules (Feedback)" href="https://bugs.ruby-lang.org/issues/7240">#7240</a>, but i feel i need to start a ticket in order to not post off topic.</p>
<p>This seems to be a big feature request, so i didn't feel confident to suggest, but when i read in <a class="issue tracker-2 status-7 priority-4 priority-default closed" title="Feature: Inheritable #included/#extended Hooks For Modules (Feedback)" href="https://bugs.ruby-lang.org/issues/7240">#7240</a> that (({Module#included})) hook can become even more hooked, i've decided to express myself.</p>
<p>=== Proposal</p>
<p>In my opinion, the most common use case for the "(({included}))" hook in modules is adding class methods. However, to me this looks hackish and hard to follow. I would have preferred if there was a way to define both instance-level and class-level behavior in a module and include both at once. Here is an API i would suggest:</p>
<p>module M<br>
def foo<br>
'Foo'<br>
end</p>
<pre><code>def base.bar # here a fictional private method Module#base is called
'Bar'
end
</code></pre>
<p>end</p>
<p>class C<br>
include M<br>
end</p>
<p>a = C.new<br>
a.foo # => 'Foo'<br>
C.bar # => 'Bar'</p>
<p>This means that a module would need to store 2 method tables, one as usual, and a second one defined as singleton methods on some object returned by some private method, called for example (({Module#base})). Since ordinary objects have no method table, classes have one method table, why not to allow modules to have 2 method tables?</p>
<p>=== Relevant considerations</p>
<ol>
<li>
<p>Talking about method tables, maybe if objects were allowed to have one, there would be no need for meta-classes? (Then classes would have 2 method tables, modules would have 3, and in fact methods and method tables could be regarded as kinds of attributes.) It looks to me like meta-class is simply there to make up for the fact that objects are not allowed to keep their own methods.</p>
</li>
<li>
<p>Allowing modules to have more method tables than classes may look like breaking the inheritance (({Class < Module})), but to me this inheritance does not look like a good idea anyway. For example, a module can be included, but a class cannot. To me, class looks like an object factory, but a module like a container of parts that can be unpacked and mounted onto a class.</p>
</li>
</ol>
<p>=== Irrelevant considerations</p>
<p>I think that from the point of view of English, the method name "(({included}))" is not consistent with the method name "(({extended}))" (the <em>module</em> is included, but the <em>base</em> is extended).</p>
<p>I would have preferred if the word "(({extend}))" was used instead of "(({include}))" when "including" one module into another, as this operation seems somewhat different from including a module into a class. I understand that it makes no sense to discuss this now, when (({extend})) is already has its fixed meaning.<br>
=end</p> Ruby master - Feature #7220 (Open): Separate IO#dup, StringIO#initialize_copy from dup(2)https://bugs.ruby-lang.org/issues/72202012-10-27T03:38:14Zbrixen (Brian Shirai)brixen@gmail.com
<p>Calling StringIO#initialize_copy causes the two objects to share the position, and eof status.</p>
<p>Is this a bug?</p>
<p>sasha:rubinius brian$ irb<br>
1.9.3p286 :001 > require 'stringio'<br>
=> true<br>
1.9.3p286 :002 > a = StringIO.new "abcdefuq"<br>
=> #<a href="StringIO:0x00000101016a88" class="external">StringIO:0x00000101016a88</a><br>
1.9.3p286 :003 > b = StringIO.new<br>
=> #<a href="StringIO:0x00000101010728" class="external">StringIO:0x00000101010728</a><br>
1.9.3p286 :004 > b.send :initialize_copy, a<br>
=> #<a href="StringIO:0x00000101010728" class="external">StringIO:0x00000101010728</a><br>
1.9.3p286 :005 > a.pos<br>
=> 0<br>
1.9.3p286 :006 > b.pos<br>
=> 0<br>
1.9.3p286 :007 > b.getc<br>
=> "a"<br>
1.9.3p286 :008 > a.pos<br>
=> 1<br>
1.9.3p286 :009 > a.getc<br>
=> "b"<br>
1.9.3p286 :010 > b.pos<br>
=> 2<br>
1.9.3p286 :011 > b.read<br>
=> "cdefuq"<br>
1.9.3p286 :012 > a.eof?<br>
=> true</p>
<p>Thanks,<br>
Brian</p> Ruby master - Feature #7149 (Open): Constant magic for everyone.https://bugs.ruby-lang.org/issues/71492012-10-13T02:46:15ZAnonymous
<p>I noticed that certain objects have constant magic: When they are first assigned to a constant, they acquire a name property equal to the constant name string. I only know about Class and Struct objects behaving this way. I like this behavior, because I like to be able to say something like:</p>
<p>Adenosine = ChemicalSpecies.new initial_concentration: 5.micromolar<br>
Adenosine.name #=> "Adenosine"</p>
<p>I like it so much, that I wrote a library (I call it ConstantMagicErsatz) for myself that searches whole namespace for the new objects assigned to constants. But searching whole wild namespace has its pitfalls. It is a wildly difficult workaround to get the candy I want. I am dreaming about just being able to say:</p>
<p>class ChemicalSpecies<br>
constant_magic true<br>
end</p>
<p>and imbue ChemicalSpecies with the same constant magic ability that Class and Struct classes have. Could it be made possible, please?</p> Ruby master - Feature #7148 (Assigned): Improved Tempfile w/o DelegateClasshttps://bugs.ruby-lang.org/issues/71482012-10-12T14:04:07ZGlass_saga (Masaki Matsushita)glass.saga@gmail.com
<p>I propose improved <code>Tempfile</code> without <code>DelegateClass()</code>.<br>
Present <code>Tempfile</code> has following problems.</p>
<ol>
<li>
<p>confusing inspect</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Tempfile</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">)</span> <span class="c1">#=> #<File:/tmp/foo20121012-6762-12w11to></span>
<span class="n">t</span><span class="p">.</span><span class="nf">is_a?</span> <span class="no">File</span> <span class="c1">#=> false</span>
</code></pre>
</li>
<li>
<p><code>#dup</code> doesn't duplicate <code>IO</code></p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Tempfile</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">)</span>
<span class="n">t</span><span class="p">.</span><span class="nf">dup</span><span class="p">.</span><span class="nf">close</span>
<span class="n">t</span><span class="p">.</span><span class="nf">read</span> <span class="c1">#=> IOError: closed stream</span>
</code></pre>
</li>
<li>
<p>finalizer performs unlink even when it has been duplicated</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">t</span> <span class="o">=</span> <span class="no">Tempfile</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">)</span>
<span class="n">path</span> <span class="o">=</span> <span class="n">t</span><span class="p">.</span><span class="nf">path</span> <span class="c1">#=> "/tmp/foo20121012-7533-1q537gq"</span>
<span class="no">File</span><span class="p">.</span><span class="nf">exist?</span> <span class="n">path</span> <span class="c1">#=> true</span>
<span class="n">tt</span> <span class="o">=</span> <span class="n">t</span><span class="p">.</span><span class="nf">dup</span>
<span class="n">t</span> <span class="o">=</span> <span class="kp">nil</span>
<span class="no">GC</span><span class="p">.</span><span class="nf">start</span>
<span class="no">File</span><span class="p">.</span><span class="nf">exist?</span> <span class="n">path</span> <span class="c1">#=> false</span>
</code></pre>
</li>
</ol>
<p>I think these problems caused by using <code>DelegateClass()</code>.<br>
Therefore, I made a patch to resolve the problems.<br>
The patched Tempfile class is a subclass of File.</p> Ruby master - Feature #7132 (Assigned): Alternation between named / ordered method arguments and ...https://bugs.ruby-lang.org/issues/71322012-10-09T21:17:44ZAnonymous
<p>=begin<br>
Hi everyone. I am using Ruby for >1 year and I would like to share with you my dreams regarding the named method arguments planned for 2.0. Let us imagine a class Thief with 3 properties (name, hit_points and dexterity), which has constructor #new_thief:</p>
<pre><code>new_thief name: "John Fingers", hit_points: 14, dexterity: 15
</code></pre>
<p>I dream about this constructor accepting alternative syntax:</p>
<pre><code>new_thief "John Fingers", hit_points: 14, dexterity: 15
</code></pre>
<p>and accepting synonyms (aliases) :hp for :hit_points and :dex for dexterity:</p>
<pre><code>new_thief "John Fingers", hp: 14, dex: 15
</code></pre>
<p>To explain my motivation, I am creating a DSL in biology. I am facing the challenge of explaining to my colleagues why is it better than their current Java app. Biologists love synonyms, and I'd like the users calling constructors for biological objects to have freedom to use the synonym they like. Of course, I can already achieve it in 1.9.3:</p>
<pre><code>def new_thief *args
oo = args.extract_options!
raise ArgumentError if args[0] and oo[:name] and args[0] != oo[:name]
name = args[0] || oo[:name] || "John Doe"
raise ArgumentError if oo[:hp] and oo[:hit_points] and oo[:hp] != oo[:hit_points]
hp = oo[:hp] || oo[:hit_points] || 9
raise ArgumentError if oo[:dex] and oo[:dexterity] and oo[:dex] != oo[:dexterity]
dex = oo[:dex] || oo[:dexterity] || 11
Thief.new( name: name, hit_points: hp, dexterity: dex )
end
</code></pre>
<p>But I find myself doing this over and over, and even if I write a library to make it easier, it's still too cumbersome.</p>
<p>Proposal no. 1: I propose that alternation between named / ordered arguments and aliases (synonyms) for named method arguments be catered for already by core syntax.</p>
<p>Proposal no. 2: I propose that the syntax for this be as follows:</p>
<pre><code>def new_thief( name=**:name="John Doe", hp: **:hit_points=14, dex: **:dexterity=15 )
Thief.new name: name, hit_points: hp, strength: str, dexterity: dex
end
</code></pre>
<p>where expressions **:arg_name would refer to the named argument :arg_name.</p>
<p>Please judge the two proposals independently. I really dream about having the alternation between named / ordered arguments and aliases for named arguments in Ruby 2.0. But I feel less sure that the syntax **:arg_name that I am proposing is the best possible syntax for this. Mind me, I don't think it is bad, I am just not sure it is <em>best</em>.</p>
<p>PS: Please forgive me suggesting such a complicated feature, while being unable to write a single line in C.<br>
=end</p> Ruby master - Feature #7121 (Assigned): Extending the use of `require'https://bugs.ruby-lang.org/issues/71212012-10-09T10:09:29Zmjones (Morgan Jones)integ3rs@gmail.com
<p>=begin<br>
I was playing with Ruby tonight and thought up an interesting idea to make (({require})) a bit better, so you can load multiple files sequentially using one method call.</p>
<p>Currently, (({require})) supports one argument, and throws a (({TypeError})) if you pass an array:</p>
<p>irb(main):001:0> require %w(json yaml)<br>
TypeError: can't convert Array into String</p>
<p>However, there's a way to patch Kernel that makes it respond to multiple objects passed in an (({Array})).</p>
<p>module Kernel<br>
@@require = method :require</p>
<p>def require *args<br>
args.flatten!<br>
args.collect! do |a|<br>
raise ArgumentError.new "arguments to `require' must be strings or symbols" unless a.is_a?(String) || a.is_a?(Symbol)<br>
@@require.call a.to_s<br>
end</p>
<pre><code> args.length == 1 ? args.first : args
</code></pre>
<p>end<br>
end</p>
<p>The new behavior doesn't actually require the modification of any code that calls (({require})) (pretty much anything, really), and new code can take advantage of the new functionality instantly.</p>
<p>irb> require %w(json yaml)<br>
=> [true, false]<br>
irb> require :pp<br>
=> false<br>
irb> require 'rails'<br>
=> true<br>
irb> require %w(json yaml), :pp, 'rails'<br>
=> [true, false, false, true]<br>
=end</p>
<p>Thanks for considering this.</p> Ruby master - Feature #7106 (Open): FileUtils.touch should allow touching the symlink itself rath...https://bugs.ruby-lang.org/issues/71062012-10-04T19:32:57Zcirrusthinking (Alessandro Diaferia)alessandro@cirrusthinking.eu
<p>Most systems support POSIX lutimes sys call that allows a symlink to be touched. I'd like to see this feature implemented.<br>
Unfortunately I'd like to see this feature on Solaris as soon as possible but I cannot see lutimes syscall supported there.</p> Ruby master - Feature #7087 (Assigned): ::ConditionVariable#wait does not work with Monitor becau...https://bugs.ruby-lang.org/issues/70872012-09-30T00:19:32Zrklemme (Robert Klemme)shortcutter@googlemail.com
<p>See program attached to bug <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: ConditionVariable#wait has meaningless return value (Assigned)" href="https://bugs.ruby-lang.org/issues/7086">#7086</a>: timeout_4 always throws:</p>
<p>ERROR: method "timeout_4": #<NoMethodError: private method `sleep' called for #<a href="Monitor:0x87e49f8" class="external">Monitor:0x87e49f8</a>></p>
<p>$ irb19 -r monitor<br>
irb(main):001:0> Monitor.new.method(:sleep)<br>
=> #<Method: Monitor(Kernel)#sleep><br>
irb(main):002:0> Monitor.instance_methods.grep /sleep/<br>
=> []</p> Ruby master - Feature #7086 (Assigned): ConditionVariable#wait has meaningless return valuehttps://bugs.ruby-lang.org/issues/70862012-09-30T00:14:11Zrklemme (Robert Klemme)shortcutter@googlemail.com
<p>I consider this an API bug: when invoked with a timeout value the caller cannot distinguish from the return value whether the condition has been signaled or the time has run out. Consider how Java does it: <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#await(long,%20java.util.concurrent.TimeUnit)" class="external">http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#await(long,%20java.util.concurrent.TimeUnit)</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#awaitUntil(java.util.Date)" class="external">http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#awaitUntil(java.util.Date)</a></p>
<p>There's another issue exhibited through the script but I will create a separate ticket for this.</p> Ruby master - Feature #7082 (Open): Process.kill 0 in windows can return spurious successhttps://bugs.ruby-lang.org/issues/70822012-09-28T16:29:13Zrogerdpack (Roger Pack)rogerpack2005@gmail.com
<blockquote>
<blockquote>
<p>a = IO.popen('ls "."', 'w')<br>
=> #<IO:fd 4><br>
a.pid<br>
=> 2104<br>
Process.kill 0, 2104<br>
=> 1 # should raise an exception since that process is dead now, shouldn't it? [it can be checked with GetExitCodeProcess != STILL_ACTIVE) ?</p>
</blockquote>
</blockquote>
<p>Thanks!<br>
-r</p> Ruby master - Feature #7060 (Open): Broaden support for chmodhttps://bugs.ruby-lang.org/issues/70602012-09-24T03:10:54Ztonysidaway (Tony Sidaway)tonysidaway@gmail.com
<p>Currently file permission bit features in all Ruby versions include only chmod and (if supported by the target platform's C library) lchmod. lchmod is not supported by all platforms, but where it is not the Posix function fchmodat usually supplies similar functionality. Suggest that this be included.</p>
<p>See <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/chmod.html" class="external">http://pubs.opengroup.org/onlinepubs/9699919799/functions/chmod.html</a></p> Ruby master - Feature #6973 (Assigned): Add an #integral? method to Numeric to test for whole-num...https://bugs.ruby-lang.org/issues/69732012-09-04T06:03:43Zregularfry (Alex Young)alex@blackkettle.org
<p>Numeric#integer? checks whether an instance is an Integer. It is often useful to check whether the value of a non-Integer variable is actually a whole number, and the #integer? method doesn't help here.</p>
<p>This patch adds Numeric#integral?, which performs this check.</p> Ruby master - Feature #6946 (Open): FIPS support?https://bugs.ruby-lang.org/issues/69462012-08-28T21:31:30Zvo.x (Vit Ondruch)v.ondruch@tiscali.cz
<p>=begin<br>
Hi, running the test suite on FIPS enabled system using</p>
<p>$ find test/ -type f -name test_*.rb -exec make test-all TESTS="-v '{}'" ;</p>
<p>command with patch from <a class="issue tracker-1 status-5 priority-4 priority-default closed" title="Bug: [PATCH] Increase DH key size to fix test suite in FIPS mode (Closed)" href="https://bugs.ruby-lang.org/issues/6938">#6938</a> applied, it gives me a plenty of errors (see attached output.txt file). There are two kind of errors as far as I understand, some are more or less test suite errors (e.g. <a class="issue tracker-1 status-5 priority-4 priority-default closed" title="Bug: [PATCH] Increase DH key size to fix test suite in FIPS mode (Closed)" href="https://bugs.ruby-lang.org/issues/6938">#6938</a>), which should be easy to fix, while some others (e.g. <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: pstore in FIPS mode (Closed)" href="https://bugs.ruby-lang.org/issues/6943">#6943</a>) would need bigger changes.</p>
<p>Is there any chance that Ruby will provide better support for FIPS and there errors get fixed?<br>
=end</p> Ruby master - Feature #6869 (Open): Do not treat `_` parameter exceptionallyhttps://bugs.ruby-lang.org/issues/68692012-08-15T06:50:54Zalexeymuranov (Alexey Muranov)
<p>I started by commenting on <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: Don't warn for unused variables starting with _ (Closed)" href="https://bugs.ruby-lang.org/issues/6693">#6693</a>, but i have realized that this is a slightly different request.</p>
<p>I propose to not treat the variable name "<code>_</code>" exceptionally. Current behavior:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="p">{</span><span class="mi">0</span><span class="o">=></span><span class="mi">1</span><span class="p">}.</span><span class="nf">each_with_index</span> <span class="p">{</span> <span class="o">|</span><span class="n">_</span><span class="p">,</span><span class="n">_</span><span class="o">|</span> <span class="nb">p</span> <span class="n">_</span> <span class="p">}</span> <span class="c1"># [0, 1]</span>
</code></pre>
<p>prints "[0, 1]", but</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="p">{</span><span class="mi">1</span><span class="o">=></span><span class="mi">2</span><span class="p">}.</span><span class="nf">each_with_index</span> <span class="p">{</span> <span class="o">|</span><span class="n">x</span><span class="p">,</span><span class="n">x</span><span class="o">|</span> <span class="nb">p</span> <span class="n">x</span> <span class="p">}</span> <span class="c1"># SyntaxError: (eval):2: duplicated argument name</span>
</code></pre>
<p>raises "SyntaxError: (eval):2: duplicated argument name".</p>
<p>Similarly for methods:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">)</span>
<span class="n">_</span>
<span class="k">end</span>
<span class="n">f</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="c1"># => 0</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="n">x</span>
<span class="k">end</span> <span class="c1"># => SyntaxError: (eval):2: duplicated argument name</span>
</code></pre>
<p>Observe also that the use of repeated <code>_</code> parameter is not consistent between methods and blocks: for methods the value is the first assigned value, and for blocks it is the array of all the assigned values.</p>
<ol>
<li>I propose to use the same rule for all variables, without distinguishing <code>_</code> specially.</li>
</ol>
<p>In particular i propose to allow to repeat any variable, not only <code>_</code>, in block or method arguments without raising an error.</p>
<p>There may be several solutions what the repeated argument will hold: it may hold the array of all assigned values, the first assigned value, the last assigned value, the first non-nil assigned value, or the last non-nil assigned value.</p>
<ol start="2">
<li>
<p>I propose to treat repeated arguments in methods and in blocks the same way (do not know which one).</p>
</li>
<li>
<p>For unused variables i propose to introduce a special placeholder, for example "<code>-</code>" not followed by anything other than a delimiter (comma or bracket):</p>
</li>
</ol>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="n">each_with_index</span> <span class="p">{</span> <span class="o">|-</span><span class="p">,</span> <span class="n">value</span><span class="o">|</span> <span class="nb">puts</span> <span class="n">value</span> <span class="p">}</span>
<span class="o">-</span><span class="p">,</span> <span class="o">-</span><span class="p">,</span> <span class="n">suffix</span> <span class="o">=</span> <span class="n">parse</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
</code></pre> Ruby master - Feature #6857 (Assigned): bigdecimal/math BigMath.E/BigMath.exp R. P. Feynman inspi...https://bugs.ruby-lang.org/issues/68572012-08-11T23:46:18Zroyaltm (Rafał Michalski)
<p>The algorythms to calculate E and exp programmed in BigMath module are the very straightforward interpretation of the series 1 + x + x^2/2! +<br>
x^3/3! + ....<br>
Therefore they are slow.</p>
<p>Try it yourself:</p>
<pre><code> require 'bigdecimal/math'
def timer; s=Time.now; yield; puts Time.now-s; end
timer { BigMath.E(1000) } #-> 0.038848
timer { BigMath.E(10000) } #-> 16.526972
timer { BigMath.E(100000) } #-> lost patience
</code></pre>
<p>That's because every iteration divides 1 by n! and the dividend grows extremely fast.</p>
<p>In "Surely You're Joking, Mr. Feynman!" (great book, you should read it if you didn't already) R. P. Feynman said:</p>
<p>"One day at Princeton I was sitting in the lounge and overheard some mathematicians talking about the series for e^x, which is 1 + x + x^2/2! +<br>
x^3/3! Each term you get by multiplying the preceding term by x and dividing by the next number. For example, to get the next term after x^4/4! you<br>
multiply that term by x and divide by 5. It's very simple."</p>
<p>Yes it's very simple indeed. Why it's not been applied in such a great, modern and popular language? Is it because people just forget about simple solutions today?</p>
<p>Here is a Feynman's optimized version of BigMath.E:</p>
<pre><code> def E(prec)
raise ArgumentError, "Zero or negative precision for E" if prec <= 0
n = prec + BigDecimal.double_fig
y = d = i = one = BigDecimal('1')
while d.nonzero? && (m = n - (y.exponent - d.exponent).abs) > 0
m = BigDecimal.double_fig if m < BigDecimal.double_fig
d = d.div(i, m)
i += one
y += d
end
y
end
</code></pre>
<p>Now, let's put it to the test:</p>
<pre><code> (1..1000).all? {|n| BigMath.E(n).round(n) == E(n).round(n) }
=> true
BigMath.E(10000).round(10000) == E(10000).round(10000)
=> true
</code></pre>
<p>What about the speed then?</p>
<pre><code> timer { E(1_000) } #-> 0.003832 ~ 10 times faster
timer { E(10_000) } #-> 0.139862 ~ 100 times faster
timer { E(100_000) } #-> 8.787411 ~ dunno?
timer { E(1_000_000) } #-> ~11 minutes
</code></pre>
<p>The same simple rule might be applied to BigDecimal.exp() which originally uses the same straightforward interpretation of power series.<br>
Feynman's pure ruby version of BigMath.exp (the ext version seems now pointless anyway):</p>
<pre><code> def exp(x, prec)
raise ArgumentError, "Zero or negative precision for exp" if prec <= 0
x = case x
when Float
BigDecimal(x, prec && prec <= Float::DIG ? prec : Float::DIG + 1)
else
BigDecimal(x, prec)
end
one = BigDecimal('1', prec)
case x.sign
when BigDecimal::SIGN_NaN
return BigDecimal::NaN
when BigDecimal::SIGN_POSITIVE_ZERO, BigDecimal::SIGN_NEGATIVE_ZERO
return one
when BigDecimal::SIGN_NEGATIVE_FINITE
x = -x
inv = true
when BigDecimal::SIGN_POSITIVE_INFINITE
return BigDecimal::INFINITY
when BigDecimal::SIGN_NEGATIVE_INFINITE
return BigDecimal.new('0')
end
n = prec + BigDecimal.double_fig
if x.round(prec) == one
y = E(prec)
else
y = d = i = one
while d.nonzero? && (m = n - (y.exponent - d.exponent).abs) > 0
m = BigDecimal.double_fig if m < BigDecimal.double_fig
d = d.mult(x, m).div(i, m)
i += one
y += d
end
end
y = one.div(y, n) if inv
y.round(prec - y.exponent)
end
(1..1000).all? {|n| exp(E(n),n) == BigMath.exp(BigMath.E(n),n) }
# => true
(1..1000).all? {|n| exp(-E(n),n) == BigMath.exp(-BigMath.E(n),n) }
# => true
(-10000..10000).all? {|n| exp(BigDecimal(n)/1000,100) == BigMath.exp(BigDecimal(n)/1000,100) }
# => true
(1..1000).all? {|n| exp(BigMath.PI(n),n) == BigMath.exp(BigMath.PI(n),n) }
# => true
timer { BigMath.exp(BigDecimal('1').div(3, 10), 100) } #-> 0.000496
timer { exp(BigDecimal('1').div(3, 10), 100) } #-> 0.000406 faster but not that really
timer { BigMath.exp(BigDecimal('1').div(3, 10), 1_000) } #-> 0.029231
timer { exp(BigDecimal('1').div(3, 10), 1_000) } #-> 0.004554 here we go...
timer { BigMath.exp(BigDecimal('1').div(3, 10), 10_000) } #-> 12.554197
timer { exp(BigDecimal('1').div(3, 10), 10_000) } #-> 0.189462 oops :)
timer { exp(BigDecimal('1').div(3, 10), 100_000) } #-> 11.914613 who has the patience to compare?
</code></pre>
<p>Arguments with large mantissa should slow down the results of course:</p>
<pre><code> timer { BigMath.exp(BigDecimal('1').div(3, 1_000), 1_000) } #-> 0.119048
timer { exp(BigDecimal('1').div(3, 1_000), 1_000) } #-> 0.066177
timer { BigMath.exp(BigDecimal('1').div(3, 10_000), 10_000) } #-> 68.083222
timer { exp(BigDecimal('1').div(3, 10_000), 10_000) } #-> 29.439336
</code></pre>
<p>Though still two times faster than the ext version.</p>
<p>It seems Dick Feynman was not such a joker after all. I think he was a master in treating lightly "serious" things and treating very seriously things that didn't matter to anybody else.</p>
<p>I'd write a patch for ext version if you are with me. Just let me know.</p> Ruby master - Feature #6842 (Assigned): Add Optional Arguments to String#striphttps://bugs.ruby-lang.org/issues/68422012-08-07T20:24:20Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
One of the very few things I miss from the ol' php days many years ago, was the ability to easily strip arbitrary characters from the ends of string using trim(). Typically, this is whitespace characters, and #strip currently fulfils that use case, but there are also instances where it'd be nice to be able to strip any range of characters from the ends of a string. It goes well with Array#join as often when joining strings with a delimiter, you want to make sure those strings don't already begin or end with that character.</p>
<p>For a full-featured #strip, I'd like to see it have the option of accepting both an Array or String. If a string is provided, each character in that string will be stripped. If an array of strings is given, each element of the array is stripped from the ends of the string - this allows for multi-character delimiters for example. Of course you could go really nuts and supports regex as well (or instead of arrays). To demonstrate the difference...</p>
<pre><code>"<b>bold text</b>".strip("</b>") #=> "old text"
"<b>bold text</b>".strip(["<b>", "</b>"]) #=> "bold text"
"<em><b>bold text</b></em>".strip(["<b>", "</b>", "<em>", "</em>"]) #=> "bold text"
"<em><b>bold text</b></em>".strip(/<\/?.+?>/) #=> "bold text"
</code></pre>
<p>A simple real-world example; this is actually what I was wanting to do right before I came here to raise this feature request, but there's been all kinds of other use cases I've hit in the past:</p>
<pre><code>['some', '/chunked', 'path/'].map{ |v| v.strip('/') }.join('/') #=> "some/chunked/path"
</code></pre>
<p>File#join does something similar, but when you need control over the joining character, this is the way you'd do it.</p>
<p>I've lost count of how many times I've wanted this in Ruby, and there's really no nice workaround. Here's an example on StackOverflow of someone asking how to achieve this stripping behaviour in ruby: <a href="http://stackoverflow.com/questions/3453262/how-to-strip-leading-and-trailing-quote-from-string-in-ruby" class="external">http://stackoverflow.com/questions/3453262/how-to-strip-leading-and-trailing-quote-from-string-in-ruby</a></p>
<p>Obviously, you'd do the same for #lstrip and #rstrip, and all the mutable variants (#strip!, #lstrip!, #rstrip!). Looking forward to others thoughts on this one.<br>
=end</p> Ruby master - Feature #6841 (Assigned): Shorthand for Assigning Return Value of Method to Selfhttps://bugs.ruby-lang.org/issues/68412012-08-07T11:37:53Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
Quite often in Ruby, I find myself doing something like: (({my_var[:foo][:bar] = my_var[:foo][:bar].to_i})) or (({obj.foo.bar = obj.foo.bar.to_i})). Realising this, I thought of what would be a fairly nice shorthand syntax for this, which could be: (({my_var[:foo][:bar] .= to_i})). How this works should be pretty self-explanatory. The (({.=})) operator works exactly like any other assignment operator of this nature.</p>
<p>Would be nice to see this in Ruby 2.0. Wondering what others think of this?<br>
=end</p> Ruby master - Feature #6828 (Open): Constancy of Constantshttps://bugs.ruby-lang.org/issues/68282012-08-04T01:23:08Ztrans (Thomas Sawyer)
<p>=begin<br>
Could have swore there was a recent issue addressing this, but couldn't find it, so...</p>
<p>I hope by Ruby 2.0</p>
<p>module Foo::Bar::Baz</p>
<p>will be equivalent to</p>
<p>module Foo; module Bar; module Baz</p>
<p>That constant lookup doesn't work the same for both is really really really annoying.<br>
=end</p> Ruby master - Feature #6817 (Open): Partial applicationhttps://bugs.ruby-lang.org/issues/68172012-07-31T15:38:35Zcitizen428 (Michael Kohl)citizen428@gmail.com
<p>I know that what I propose here is a significant change to Ruby, but it's part of my ongoing quest to get some more functional programming features into Ruby (see also <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: Array#zip_with (Assigned)" href="https://bugs.ruby-lang.org/issues/4539">#4539</a> and <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: public #self (Closed)" href="https://bugs.ruby-lang.org/issues/6373">#6373</a>).</p>
<p>I was wondering if it would make sense to maybe introduce partial application to Ruby? So that instead of</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">2</span> <span class="p">}</span>
</code></pre>
<p>or the somewhat unwieldy</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="mi">2</span><span class="p">.</span><span class="nf">method</span><span class="p">(:</span><span class="o">+</span><span class="p">))</span>
</code></pre>
<p>one could just write</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="mi">2</span><span class="p">.</span><span class="nf">+</span><span class="p">)</span>
</code></pre>
<p>which I think has a quite rubyish feel to it. I have a POC implementation in Ruby (I tried it with various <code>Fixnum</code> methods) over at <a href="http://citizen428.net/blog/2012/07/30/ruby-left-section-for-infix-operators" class="external">my blog</a>, but that was just a quick hack and obviously I don't want to monkey-patch every method with arity 1, but it was a nice way of exploring possible syntax.</p> Ruby master - Feature #6811 (Assigned): File, Dir and FileUtils should have bang-versions of sing...https://bugs.ruby-lang.org/issues/68112012-07-29T20:34:08Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>I found that often write<br>
Dir.mkdir(folder) unless Dir.exist? folder<br>
and similar code for rm, rm_rf and so on<br>
We can simply make bang-versions like<br>
def Dir.mkdir!(folder, permissions=0744)<br>
Dir.mkdir(folder, permissions) unless Dir.exist? folder</p>
<a name="or-another-alternative-Dirmkdirfolder-permissions-rescue-false"></a>
<h1 >or another alternative Dir.mkdir(folder, permissions) rescue false<a href="#or-another-alternative-Dirmkdirfolder-permissions-rescue-false" class="wiki-anchor">¶</a></h1>
<p>end</p> Ruby master - Feature #6810 (Assigned): `module A::B; end` is not equivalent to `module A; module...https://bugs.ruby-lang.org/issues/68102012-07-29T03:55:09Zalexeymuranov (Alexey Muranov)
<p>Is this the expected behavior? To me, it is rather surprising:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="no">N</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">module</span> <span class="nn">A</span>
<span class="k">module</span> <span class="nn">B</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">f</span><span class="p">;</span> <span class="no">N</span><span class="p">;</span> <span class="k">end</span>
<span class="k">end</span>
<span class="no">N</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 1</span>
<span class="no">N</span> <span class="o">=</span> <span class="mi">0</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 0</span>
<span class="no">A</span><span class="o">::</span><span class="no">N</span> <span class="o">=</span> <span class="mi">1</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 1</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="o">::</span><span class="no">N</span> <span class="o">=</span> <span class="mi">2</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 2</span>
</code></pre>
<p>but</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="no">N</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">module</span> <span class="nn">A</span><span class="p">;</span> <span class="k">end</span>
<span class="k">module</span> <span class="nn">A::B</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">f</span><span class="p">;</span> <span class="no">N</span><span class="p">;</span> <span class="k">end</span>
<span class="k">end</span>
<span class="k">module</span> <span class="nn">A</span>
<span class="no">N</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 0</span>
<span class="no">N</span> <span class="o">=</span> <span class="mi">0</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 0</span>
<span class="no">A</span><span class="o">::</span><span class="no">N</span> <span class="o">=</span> <span class="mi">1</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 0</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="o">::</span><span class="no">N</span> <span class="o">=</span> <span class="mi">2</span>
<span class="no">A</span><span class="o">::</span><span class="no">B</span><span class="p">.</span><span class="nf">f</span> <span class="c1"># => 2</span>
</code></pre> Ruby master - Feature #6802 (Assigned): String#scan should have equivalent yielding MatchDatahttps://bugs.ruby-lang.org/issues/68022012-07-27T16:17:42Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>Ruby should have method to obtain not an array of arrays but of MatchData objects. It can help in obtaining named groups:</p>
<p>pattern = /x: (?\d+) y:(?\d+)/<br>
polygon = []<br>
text.scan_for_pattern(pattern){|m| polygon << Point.new(m[:x], m[:y]) }</p>
<p>Not to break existing code we need unique name. Ideas? May be #each_match</p> Ruby master - Feature #6783 (Open): Infinite loop in inspect, not overriding inspect, to_s, and n...https://bugs.ruby-lang.org/issues/67832012-07-23T23:22:31Zgarysweaver (Gary Weaver)garysweaver@gmail.com
<p>In Ruby 1.9.3p194 in Rails 3.2.6 in rails console, in my script I'm calling inspect on a Ruby object and even though I'm not overriding inspect, to_s, and there are no known circular references, inspect is going into an infinite loop locking Ruby up with 100% CPU usage.</p>
<p>At first, I would think this problem is probably outside of Ruby and either in my code or in a gem that I'm using, however the problem is that using the Debugger gem, if I set a breakpoint above the issue and use "s" (by itself) to step into the line where it calls inspect, it locks up there, so I can't debug the issue. When I do that I hit ctrl-c, I'm in .../.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:</p>
<pre><code> 64 trap("SIGINT") do
=> 65 irb.signal_handle
66 end
</code></pre>
<p>and breaking out of that, or if I don't step into it and I break out of it, I see:</p>
<pre><code>path_to_script/script_name.rb:739:in `call'
path_to_script/script_name.rb:739:in `inspect'
path_to_script/script_name.rb:739:in `inspect'
...
(~100 times)
path_to_script/script_name.rb:739:in `block (2 levels) in my_method_name'
</code></pre>
<p>In a situation like this, how can I debug the issue? Is there anything in the inspect method that could causing this behavior?</p>
<p>I think the most likely culprit is some bad code on my part in the script, but unfortunately I can't debug it when the debugger can't step into inspect.</p>
<p>Thanks for any help you can provide.</p> Ruby master - Feature #6769 (Assigned): rbinstall.rb: install both src and batch files separetelyhttps://bugs.ruby-lang.org/issues/67692012-07-22T10:04:13Zluislavena (Luis Lavena)luislavena@gmail.com
<p>=begin<br>
Hello,</p>
<p>Current behavior of rbinstall.rb is to concat bin scripts (erb, rake, rdoc, etc) along with a batchfile stub in a single file, resulting in erb.bat, rdoc.bat etc.</p>
<p>Those files works OK when invoked directly, but they do not support the following scenarios:</p>
<ul>
<li>
<p>Invoke it like "ruby -S rake", which looks for extension-less script in the path (and that does not exist)</p>
</li>
<li>
<p>Cannot invoke those scripts from another script, example, from Rake, do "ruby 'rdoc'" will not work.</p>
</li>
</ul>
<p>To circumvent this issue at RubyInstaller, we copied the original bin scripts and replaced the batchfile stubs with simple ones:</p>
<p><a href="https://github.com/oneclick/rubyinstaller/blob/master/recipes/interpreter/ruby19.rake#L188-197" class="external">https://github.com/oneclick/rubyinstaller/blob/master/recipes/interpreter/ruby19.rake#L188-197</a></p>
<p>===</p>
<p>I would like to change rbinstall.rb to copy over verbatim bin scripts and simple batchfiles stubs.</p>
<p>That will solve the above two issues I mentioned plus open the scenario to a easy executable-based launcher, similar to gem-exefy:</p>
<p><a href="https://github.com/bosko/gem-exefy" class="external">https://github.com/bosko/gem-exefy</a></p>
<p>To have identifiable scripts in list of process plus, customized firewall rules and remove the dreaded "Terminate batch job" prompt.</p>
<p>Before I start working on this, I wanted to know what do you think about this?</p>
<p>Thanks in advance for your feedback and looking forward your responses.<br>
=end</p> Ruby master - Feature #6758 (Open): Object#sequencehttps://bugs.ruby-lang.org/issues/67582012-07-20T13:38:09Zmerborne (kyo endo)
<p>=begin</p>
<p>== Object#sequence</p>
<p>Let me propose a new method ((<em>Object#sequence</em>)).</p>
<p>次のような実装の((<em>Object#sequence</em>))を提案します。</p>
<pre><code>class Object
def sequence(init=true, &blk)
x = self
Enumerator.new do |y|
y << x if init
loop { y << (x = yield x) }
end
end
end
</code></pre>
<p>((<em>sequence</em>)) generate a sequence by applying a block recursively to the receiver object. The result is wrapped with a Enumerator object, thus it is set under lazy evaluation.</p>
<p>((<em>sequence</em>))は、そのレシーバオブジェクトを初期値として、渡されたブロック(漸化式)を繰り返し適用してシーケンスを生成します。適用の結果はEnumeratorオブジェクトでラップされているので、遅延評価されます。</p>
<p>== Usage;</p>
<p>使い方を示します。</p>
<pre><code>1.sequence { |x| x + 2 }.take(10) # => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
3.sequence { |x| x * 2 }.take(10) # => [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
[0, 1].sequence { |a, b| [b, a + b] }.take(10).map(&:first) # => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0, 1, 1].sequence { |a, b, c| [b, c, a + b + c] }.take(10).map(&:first) # => [0, 1, 1, 2, 4, 7, 13, 24, 44, 81]
# square root 5
a = 5
eps = 0.0001
1.0.sequence { |x| (x + a/x) / 2.0 }
.each_cons(2)
.detect { |a, b| (a - b).abs < eps }[1] # => 2.236067977499978
# Excel label
'A'.sequence { |x| x.succ }.take(30) # => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD"]
# random boolean(avoid true-true sequence)
true.sequence { |prev| prev ? false : [true, false].sample }.take(20) # => [true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, false, false, true, false]
</code></pre>
<p>== Some background</p>
<p>== 提案の経緯</p>
<p>Let me explain some background of this request.</p>
<p>本件に関しては、ここに至る若干の経緯がありますので、併せて説明します。</p>
<ol>
<li>
<p>I introduced this method as ((<em>Object#repeat</em>)) on my Japanese blog.</p>
</li>
<li>
<p>私のブログにおいて、本メソッドを((<em>Object#repeat</em>))として紹介する記事を公開。</p>
</li>
</ol>
<p>((<a href="URL:http://melborne.github.com/2012/07/12/object-repeat-take-care-of-sequence/" class="external">URL:http://melborne.github.com/2012/07/12/object-repeat-take-care-of-sequence/</a>))</p>
<ol start="2">
<li>
<p>Matz tweeted to the article.</p>
<blockquote>
<p>"um.. the feature is attractive, but the name is.."</p>
</blockquote>
</li>
<li>
<p>記事に対してMatzがつぶやく。</p>
<blockquote>
<p>「うーん、昨日としては魅力的だけど、名前がなあ。」</p>
</blockquote>
</li>
</ol>
<p>((<a href="URL:https://twitter.com/yukihiro_matz/status/223790181113806848" class="external">URL:https://twitter.com/yukihiro_matz/status/223790181113806848</a>))</p>
<ol start="3">
<li>
<p>I updated the article to propose ((<em>Object#repeat_apply</em>)) or ((<em>Object#repeat_call</em>)).</p>
</li>
<li>
<p>Object#repeat_apply, Object#repeat_callを提案するべく記事を更新。</p>
</li>
<li>
<p>Matz tweeted to the article.</p>
<blockquote>
<p><a class="user active user-mention" href="https://bugs.ruby-lang.org/users/4653">@merborne (kyo endo)</a> more clear. but combining two verbs is wrong. I understand naming is difficult.</p>
</blockquote>
</li>
<li>
<p>記事に対してMatzがつぶやく。</p>
<blockquote>
<p><a class="user active user-mention" href="https://bugs.ruby-lang.org/users/4653">@merborne (kyo endo)</a> なるほど「repeat_apply」か「repeat_call」ですか。repeat単体よりは誤解を受けにくいとは思いますが、repeatって動詞とapply/callって動詞の組み合わせは感心しませんね。名前って難しい。</p>
</blockquote>
</li>
</ol>
<p>((<a href="URL:https://twitter.com/yukihiro_matz/status/224105896110866432" class="external">URL:https://twitter.com/yukihiro_matz/status/224105896110866432</a>))</p>
<ol start="5">
<li>
<p>Matz tweeted to the article.</p>
<blockquote>
<p><a class="user active user-mention" href="https://bugs.ruby-lang.org/users/4653">@merborne (kyo endo)</a> I suggest some clue lies around a word "series"..</p>
</blockquote>
</li>
<li>
<p>記事に対してMatzがつぶやく。</p>
<blockquote>
<p><a class="user active user-mention" href="https://bugs.ruby-lang.org/users/4653">@merborne (kyo endo)</a> 「級数/series」あたりに名前のヒントがありそうな。</p>
</blockquote>
</li>
</ol>
<p>((<a href="URL:https://twitter.com/yukihiro_matz/status/224106160591081472" class="external">URL:https://twitter.com/yukihiro_matz/status/224106160591081472</a>))</p>
<ol start="6">
<li>
<p>I tweeted to Matz.</p>
</li>
<li>
<p>私もつぶやく</p>
<blockquote>
<p>@yukihiro_matz you are right.. <code>repeated_apply</code> <code>repeated_call</code>?..</p>
</blockquote>
<blockquote>
<p>@yukihiro_matz たしかに.. repeated_apply repeated_callかな..</p>
</blockquote>
</li>
</ol>
<p>((<a href="URL:https://twitter.com/merborne/status/224108387653259264" class="external">URL:https://twitter.com/merborne/status/224108387653259264</a>))</p>
<pre><code>> @yukihiro_matz clue! `series_by` ?
> @yukihiro_matz ヒント! series_by ?
</code></pre>
<p>((<a href="URL:https://twitter.com/merborne/status/224108809948377088" class="external">URL:https://twitter.com/merborne/status/224108809948377088</a>))</p>
<pre><code>> @yukihiro_matz `repeated` is adjective..^^; but I don't like `repeatedly_apply`. I thought once `series_by` is good, but it would be better a method is named based on its behavior, not on its function, I think. How about `repeat_by`?
> @yukihiro_matz repeatedは形容詞でしたね^^; するとrepeatedly_applyですが、今ひとつです。series_byもいいと思ったんですが、できれば機能ではなく動作を言いたい思いがあります。そこでrepeat_byというのはどうでしょうか。
</code></pre>
<p>((<a href="URL:https://twitter.com/merborne/status/224324670764220416" class="external">URL:https://twitter.com/merborne/status/224324670764220416</a>))</p>
<p>the conversation closed..</p>
<p>会話終了..</p>
<ol start="7">
<li>Ideas from other Rubyists</li>
</ol>
<p>Some Japanese Rubyists tweeted or commented me on the name. Candidates are..</p>
<ol start="7">
<li>他のRubyistの意見</li>
</ol>
<p>名前に関し何人かのRubyistからアイディアをもらっています。リストアップします。</p>
<pre><code>iterate
recur
recurrence
recur_with
unfold
sequence
seq
</code></pre>
<p>Haskell and Scala have the same functionality with a name of ((<em>iterate</em>)).</p>
<p>なお、HaskellとScalaには同種の機能が、((<em>iterate</em>))という名前で実装されているそうです。</p>
<p>Also, @makotokuwata-san tweeted that ((<em>Kernel#seq</em>))(function style) or ((<em>Enumerator.seq()</em>))(a Class method) is better.</p>
<p>また、@makotokuwata氏よりKernel#seqのような関数形式か、Enumerator.seq()のようなクラスメソッドのほうがいいとの意見も頂いています。</p>
<pre><code>> @yukihiro_matz @merborne 初期値と漸化式から順列を作る機能なので、"sequence"か"seq"に1票。あとKernel#seq(initial,&blk)のほうが好きです。RT 「級数/series」あたりに名前のヒントがありそうな。
</code></pre>
<p>((<a href="URL:https://twitter.com/makotokuwata/status/225806204390227968" class="external">URL:https://twitter.com/makotokuwata/status/225806204390227968</a>))</p>
<p>Thank you for your consideration.</p>
<p>以上、ご検討のほどよろしくお願い致します。</p>
<p>=end</p> Ruby master - Feature #6733 (Open): New inspect frameworkhttps://bugs.ruby-lang.org/issues/67332012-07-14T18:06:18Zakr (Akira Tanaka)akr@fsij.org
<p>After we discussed <a href="http://bugs.ruby-lang.org/issues/6291" class="external">http://bugs.ruby-lang.org/issues/6291</a> at a developer meeting,<br>
we re-realized new inspect framework may be useful.</p>
<p>Problem:</p>
<ul>
<li>inspect method may generate too long string but sometimes whole string is not required.<br>
For example, first 70 characters are enough for error messages (backtrace).</li>
<li>inspect can't know a encoding to be expected.</li>
<li>inspect generates may short strings and discard them immediately.</li>
</ul>
<p>If we have a new method, inspect_to(buffer), and<br>
it (or overridden method in subclass) adds the inspected result to buffer,<br>
we can solve above problems.<br>
buffer has a method, <<.<br>
It may be a string, IO or other object.</p>
<p>For too long string, buffer itself can throw (or raise) when buffered output is reached to a specified limit.</p>
<p>For encoding, buffer can record an encoding.<br>
(p method creates a buffer object using $stdout's encoding.)</p>
<p>For small strings, in C level, we can create a rb_buffer_add(VALUE buffer, const char *p, long len) and<br>
it don't need to allocate a String object.</p>
<p>This is big change but we can preserve compatibility by following default inspect_to method:</p>
<p>class Object<br>
def inspect_to(buffer)<br>
buffer << self.inspect<br>
end<br>
end</p>
<p>If legacy class which has inspect but not inspect_to,<br>
Object#inspect_to calls inspect and use the result.</p> Ruby master - Feature #6695 (Assigned): Configuration for Thread/Fiber creationhttps://bugs.ruby-lang.org/issues/66952012-07-04T14:24:28Zko1 (Koichi Sasada)
<p>=begin<br>
= Abstract</p>
<p>With Feature <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: Thread.new without block. (Assigned)" href="https://bugs.ruby-lang.org/issues/6694">#6694</a>, the following configuration parameters should be allowed for Thread/Fiber creation.</p>
<p>Group1 (new parameters):</p>
<ul>
<li>name: Thread/Fiber name</li>
<li>vm_stack_size: VM's stack size</li>
<li>machine_stack_size: Machine stack size</li>
</ul>
<p>Group2 (existing parameters):</p>
<ul>
<li>local_storage: Initial Thread/Fiber local parameters</li>
<li>thread_group: Thread group (Thread only)</li>
<li>priority: Initial priority Thread#priority= (Thread only)</li>
<li>abort_on_exception: abort on exception (Thread only)</li>
</ul>
<p>= Background</p>
<p>With Feature <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: Thread.new without block. (Assigned)" href="https://bugs.ruby-lang.org/issues/6694">#6694</a>, we have a way to specify configurations for Thread creation. Fiber.new() don't receive any parameters now.</p>
<p>= Proposal</p>
<p>This is a initial proposal of configuration for Thread/Fiber creation.</p>
<p>Group1 (new parameters):</p>
<ul>
<li>name: Thread/Fiber name</li>
<li>vm_stack_size: VM's stack size</li>
<li>machine_stack_size: Machine stack size</li>
</ul>
<p>vm_stack_size and machine_stack_size are OS dependent (This means that it will be <em>hint</em> parameter).</p>
<p>Thread#inspect should use `name' parameter.</p>
<p>I also propose a new method Thread#name to get the thread name specified by this parameter.</p>
<p>Group2 (existing parameters):</p>
<ul>
<li>local_storage: Initial Thread/Fiber local parameters</li>
<li>thread_group: Thread group (Thread only)</li>
<li>priority: Initial priority Thread#priority= (Thread only)</li>
<li>abort_on_exception: abort on exception (Thread only)</li>
</ul>
<p>Now, we can specify Group2 parameters only <em>after</em> thread creation. With this parameter, we can specify parameters before thread creation.</p>
<p>=end</p> Ruby master - Feature #6694 (Assigned): Thread.new without block.https://bugs.ruby-lang.org/issues/66942012-07-04T13:51:11Zko1 (Koichi Sasada)
<a name="Abstract"></a>
<h1 >Abstract<a href="#Abstract" class="wiki-anchor">¶</a></h1>
<p>Support Thread.new() without block.</p>
<p>Before: <code>Thread.new(params...){|thread_local_params| ...}</code></p>
<p>After: <code>Thread.new(proc: lambda{|tl_params...| ...}, args: params..., other_thread_config...)</code></p>
<a name="Background"></a>
<h1 >Background<a href="#Background" class="wiki-anchor">¶</a></h1>
<p>Thread.new creates new Thread object and run passed block in another thread immediately. Thread.new can receive parameters and pass all parameters to block.</p>
<pre><code> Thread.new(a, b, c) do |ta, tb, tc|
# ta, tb, tc is thread local
}
</code></pre>
<p>There are some request to specify thread configurations such as stack size described in [Ruby 1.9 - Feature <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Allow dynamic Fiber stack size (Rejected)" href="https://bugs.ruby-lang.org/issues/3187">#3187</a>] (in this case, stack size for Fiber.new). However, we have no way to pass such thread configuration on the Thread.new().</p>
<a name="Proposal"></a>
<h1 >Proposal<a href="#Proposal" class="wiki-anchor">¶</a></h1>
<p>Allow Thread.new() without block. A block will be passed with proc parameter. Passed arguments will be passed with args parameter.</p>
<pre><code> # ex1
Thread.new(){...}
#=>
Thread.new(proc: -> {...})
# ex2
Thread.new(a, b, c){|ta, tb, tc| ...}
#=>
Thread.new(proc: ->(ta, tb, tc){ ... }, params: [a, b, c])
</code></pre>
<p>If you want to specify stack size, then:</p>
<p>Thread.new(stack_size: 4096, proc: proc{...}, args: [a, b, c])</p>
<p>Note that I'll make another ticket for thread (and fiber) creation parameters.</p>
<p>This change can be described with the following pseudo code:</p>
<pre><code> def Thread.new(*args, &block)
if block
Thread.new_orig(*args, &block)
else
config = args[0] || raise ArgumentError
stack_size = config[:stack_size]
# ... and process another parameters
Thread.new_orig(*config[:args], &config[:proc])
end
end
</code></pre>
<a name="Another-proposal"></a>
<h1 >Another proposal<a href="#Another-proposal" class="wiki-anchor">¶</a></h1>
<p>On the <a href="/issues/3187">[ruby-core:43385]</a>, Nahi-san proposed that if no block given on Thread.new(), then create "waiting" thread. Thread#run kicks waiting thread with parameters.</p>
<pre><code> th = Thread.new(thread_config_params)
...
th.run(params){|thread_local_params|
...
}
</code></pre>
<p>We can combine with <code>proc:</code> parameter and this proposal.<br>
If <code>Thread.new()</code> doesn't have block and <code>proc:</code> parameter, then making a waiting thread.</p>
<p>NOTE: Because we have already Thread#run, Thread#start is better than Thread#run?</p>
<a name="Note"></a>
<h1 >Note<a href="#Note" class="wiki-anchor">¶</a></h1>
<p>I don't make any survey on other languages. Please give us your comments.</p> Ruby master - Feature #6687 (Open): Enumerable#withhttps://bugs.ruby-lang.org/issues/66872012-07-02T22:38:59Zmerborne (kyo endo)
<p>=begin<br>
Let me propose <code>Enumerable#with</code> for an alias of <code>Enumerable#each_with_object</code> or replace of it.</p>
<p><code>Enumerable#each_with_object</code>のエイリアス、またはその置き換えとして、<code>Enumerable#with</code>を提案します。</p>
<p>##Reason</p>
<p>##理由</p>
<p>When you create a hash using <code>Enumerable#inject</code>, you should ensure that the block return the hash.</p>
<p><code>Enumerable#inject</code>を使ってハッシュを生成するときには、ブロックの返り値としてハッシュが返ることを保証する必要があります。</p>
<pre><code>words.inject(Hash.new(0)) { |h, word| h[word] += 1; h } # => {"You"=>3, "say"=>10, "Yes"=>1, "I"=>7, "No"=>1, "Stop"=>1, "and"=>2, "Go"=>1, "go"=>2, "Oh"=>1, "no"=>1, "Goodbye"=>2, "Hello"=>2, "hello"=>5, "don"=>2, "t"=>2, "know"=>2, "why"=>2, "you"=>2, "goodbye"=>1}
</code></pre>
<p>Many rubyists, however, hate this, and there are many discussions for it.</p>
<p>しかし、これを嫌うRubyistは多く、ネット上でその改善についての議論をしばしば見掛けます。</p>
<pre><code>Feature #5662: inject-accumulate, or Haskell's mapAccum* - ruby-trunk - Ruby Issue Tracking System http://bugs.ruby-lang.org/issues/5662
Ruby inject with intial being a hash - Stack Overflow http://stackoverflow.com/questions/9434162/ruby-inject-with-intial-being-a-hash
</code></pre>
<p><code>Enumerable#each_with_object</code> is often presented for one of the best solutions for it.</p>
<p>そしてその有力な解決策として、Enumerable#each_with_objectが提示されてきました。</p>
<pre><code>words.each_with_object(Hash.new(0)) { |word, h| h[word] += 1 } # => {"You"=>3, "say"=>10, "Yes"=>1, "I"=>7, "No"=>1, "Stop"=>1, "and"=>2, "Go"=>1, "go"=>2, "Oh"=>1, "no"=>1, "Goodbye"=>2, "Hello"=>2, "hello"=>5, "don"=>2, "t"=>2, "know"=>2, "why"=>2, "you"=>2, "goodbye"=>1}
</code></pre>
<p>However, <code>each_with_object</code> is still unfamiliar and then not used frequently. The biggest reason, I think, is its lengthy name.</p>
<p>しかし、その有用性にも拘らず、依然としてeach_with_objectの知名度および利用頻度は低いと思われます。そして、その原因は、その名前の長さにあると考えます。</p>
<p><code>each_with_object</code> is the 39th longest-name method among 754 at Ruby 1.9.3, based on following calculation;</p>
<p>以下の演算により、Ruby1.9.3の環境下でeach_with_objectは、754件中39番目に長い名前のメソッドであることが分かりました。</p>
<pre><code>methods = Module.constants.flat_map do |c|
next [] if c == :Gem
k = Module.const_get(c)
k.methods(false) + k.instance_methods(false) rescue []
end.uniq.reject { |m| "#{m}".start_with? '_deprecated' }.sort_by { |m| -m.size }
methods.size # => 754
methods.index(:each_with_object) # => 39
puts methods.take(100).group_by(&:size).to_a
</code></pre>
<p>The output is here.</p>
<p>出力です。</p>
<pre><code>26
protected_instance_methods
instance_variable_defined?
25
protected_method_defined?
24
private_instance_methods
23
class_variable_defined?
public_instance_methods
define_singleton_method
private_method_defined?
22
singleton_method_added
public_instance_method
public_method_defined?
21
instance_variable_get
instance_variable_set
remove_class_variable
20
private_class_method
repeated_combination
repeated_permutation
compare_by_identity?
19
respond_to_missing?
abort_on_exception=
public_class_method
compare_by_identity
18
undefine_finalizer
instance_variables
abort_on_exception
class_variable_get
class_variable_set
relative_path_from
17
internal_encoding
external_encoding
default_internal=
default_external=
protected_methods
singleton_methods
ascii_compatible?
16
global_variables
executable_real?
initialize_clone
each_with_object # <= Here!
require_relative
private_constant
default_external
included_modules
instance_methods
define_finalizer
default_internal
15
private_methods
fixed_encoding?
class_variables
instance_method
each_with_index
public_constant
garbage_collect
source_location
valid_encoding?
singleton_class
world_writable?
local_variables
world_readable?
method_defined?
14
readable_real?
locale_charmap
const_defined?
collect_concat
initialize_dup
add_trace_func
close_on_exec=
close_on_exec?
named_captures
set_trace_func
write_nonblock
writable_real?
each_codepoint
force_encoding
public_methods
13
const_missing
each_filename
default_proc=
set_backtrace
public_method
read_nonblock
instance_exec
absolute_path
count_objects
instance_eval
12
marshal_load
reverse_each
exclude_end?
instance_of?
make_symlink
set_encoding
block_given?
default_proc
slice_before
marshal_dump
11
rationalize
realdirpath
each_object
expand_path
with_object
</code></pre>
<p>This result shows that methods which has 15+ name length is mostly for reflection or for special purpose. <code>each_with_object</code> is a general purpose method, the name should be shorter.</p>
<p>このリストから分かることは、長さ15を超えるメソッドはその大半がリフレクション用か特殊目的用のものであるという事実です。each_with_objectはより汎用的なメソッドですから、その名前はもっと短くあるべきと考えます。現状の長さは、そのメソッドを無きものにしています。</p>
<p>I propose Enumerable#with for it. a word <code>object</code> in <code>each_with_object</code> is obvious and not necessary to spcify the purpose, because all data in Ruby is <code>object</code>. Also, a word <code>each</code> in <code>each_with_object</code> is not essential, then omittable in view of the fact that it is called to Enumerable object. I think that a word <code>with</code> still works for describing the same of <code>each_with_object</code>.</p>
<p>そこでEnumerable#withを提案します。まず、Rubyで扱われるデータはすべてオブジェクトですから、each_with_objectにおけるobjectは自明であり不要と考えます。次に、Enumerableオブジェクトに対するメソッド呼び出しという点から見て、eachも必須のものとは言えず、削除可能と考えます。そして残ったwithで十分にその目的、つまりEnumerableな要素を任意のオブジェクトと共に操作する、を意図できていると考えます。</p>
<p>Lastly, following is examples with <code>Enumerable#with</code></p>
<p>最後に、<code>Enumerable#with</code>を使った例を示します。</p>
<pre><code>Enumerable.send(:alias_method, :with, :each_with_object)
words.with(Hash.new(0)) { | word, h| h[word] += 1 } # => {"You"=>3, "say"=>10, "Yes"=>1, "I"=>7, "No"=>1, "Stop"=>1, "and"=>2, "Go"=>1, "go"=>2, "Oh"=>1, "no"=>1, "Goodbye"=>2, "Hello"=>2, "hello"=>5, "don"=>2, "t"=>2, "know"=>2, "why"=>2, "you"=>2, "goodbye"=>1}
[*1..10].with(5).map(&:*) # => [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
['ruby', 'python', 'haskell'].with('ist').map(&:+) # => ["rubyist", "pythonist", "haskellist"]
</code></pre>
<p>Thank you for your consideration.</p>
<p>ご検討の程よろしくお願い致します。</p>
<p>=end</p> Ruby master - Feature #6682 (Assigned): Add a method to return an instance attached by a singleto...https://bugs.ruby-lang.org/issues/66822012-07-01T19:22:05Zryoqun (Ryo Onodera)ryoqun@gmail.com
<p>=begin<br>
Currently, there is no easy way to get the attached instance from a singleton class. For MRI, we have to resort to writing an C extension. So it'll be useful to add an instance method to Class to return the attached instance if the given class object is a singleton class.</p>
<p>I'll show what I want in the code-wise with the following code snippet:</p>
<p>text = "I love Ruby."<br>
klass = text.singleton_class</p>
<a name="gt-ltClassString0x000000027383e8gt"></a>
<h1 >=> #<Class:#<a href="String:0x000000027383e8" class="external">String:0x000000027383e8</a>><a href="#gt-ltClassString0x000000027383e8gt" class="wiki-anchor">¶</a></h1>
<p>klass.singleton_instance # <= This is the new method.</p>
<a name="gt-I-love-Ruby"></a>
<h1 >=> "I love Ruby."<a href="#gt-I-love-Ruby" class="wiki-anchor">¶</a></h1>
<p>String.singleton_instance # <= This should return nil because String isn't a singleton class and there is no singleton instance, rather there will be many instances.</p>
<a name="gt-nil"></a>
<h1 >=> nil<a href="#gt-nil" class="wiki-anchor">¶</a></h1>
<p>As for use cases, in my case, I wanted to create a module to add class methods. And it has some state, so must be initialized properly. And it can equally be used by Class#extend and Class#include like this:</p>
<p>module Countable<br>
attr_reader(:count)</p>
<pre><code>class << self
def extended(extended_class)
p("extending #{extended_class}")
super
initialize_state(extended_class)
end
def included(included_class)
p("including #{included_class}")
super
if included_class.singleton_instance # <= Currently, I can't do this.
initialize_state(included_class.singleton_instance)
end
end
private
def initialize_state(object)
p("initializing state of #{object}")
object.instance_variable_set(:@count, 0)
end
end
</code></pre>
<p>end</p>
<p>class Person<br>
extend(Countable)<br>
end</p>
<p>class Book<br>
class << self<br>
include(Countable)<br>
end<br>
end</p>
<p>p(Person.count)<br>
p(Book.count)</p>
<a name="gt-extending-Person"></a>
<h1 >=> "extending Person"<a href="#gt-extending-Person" class="wiki-anchor">¶</a></h1>
<a name="gt-initializing-state-of-Person"></a>
<h1 >=> "initializing state of Person"<a href="#gt-initializing-state-of-Person" class="wiki-anchor">¶</a></h1>
<a name="gt-including-ClassBook"></a>
<h1 >=> "including #<a href="Class:Book" class="external">Class:Book</a>"<a href="#gt-including-ClassBook" class="wiki-anchor">¶</a></h1>
<a name="gt-initializing-state-of-Book"></a>
<h1 >=> "initializing state of Book"<a href="#gt-initializing-state-of-Book" class="wiki-anchor">¶</a></h1>
<a name="gt-0"></a>
<h1 >=> 0<a href="#gt-0" class="wiki-anchor">¶</a></h1>
<a name="gt-0-2"></a>
<h1 >=> 0<a href="#gt-0-2" class="wiki-anchor">¶</a></h1>
<p>Others wanted this functionality as shown by ((<this stackoverflow page|URL:<a href="http://stackoverflow.com/questions/7053455/given-a-ruby-metaclass-how-do-i-get-the-instance-to-which-it-is-attached%3E" class="external">http://stackoverflow.com/questions/7053455/given-a-ruby-metaclass-how-do-i-get-the-instance-to-which-it-is-attached></a>)). Also, I found several actual C-extensions for this kind of functionality on the wild browsing ((<a search result|URL:<a href="https://github.com/search?q=rb_iv_get+__attached__&repo=&langOverride=&start_value=1&type=Code&language=C%3E" class="external">https://github.com/search?q=rb_iv_get+__attached__&repo=&langOverride=&start_value=1&type=Code&language=C></a>)) on github.</p>
<ul>
<li>((<eigen|URL:<a href="https://github.com/elliottcable/refinery/blob/853dcc2254557200d1d6be4cb9c105e8fa9d01a9/ext/eigen/eigen.c#L12%3E" class="external">https://github.com/elliottcable/refinery/blob/853dcc2254557200d1d6be4cb9c105e8fa9d01a9/ext/eigen/eigen.c#L12></a>))</li>
<li>((<mult|URL:<a href="https://github.com/banister/mult/blob/6a1d0bdd383e7e231c5b7c2c718204dfb6ba28ca/ext/mult/mult.c#L43%3E" class="external">https://github.com/banister/mult/blob/6a1d0bdd383e7e231c5b7c2c718204dfb6ba28ca/ext/mult/mult.c#L43></a>))</li>
</ul>
<p>Thanks for creating a great language. Especially I love its meta-programming capability. I'd wish this feature to lead to better meta-programming capability of Ruby.<br>
=end</p> Ruby master - Feature #6671 (Assigned): File.split_all and File.split_roothttps://bugs.ruby-lang.org/issues/66712012-06-30T04:28:57Ztrans (Thomas Sawyer)
<p>=begin<br>
Is there a method for this already?</p>
<p>File.split_all('a/b/c') #=> ['a','b','c']</p>
<p>If not I propose it be added. I've had need of such more than a few times.</p>
<p>It's too bad that File.split can't do this, as it would make more sense. And the current method be called <code>split_base</code>.</p>
<p>In addition <code>split_root</code> would be helpful.</p>
<p>root, path = File.split_all('a/b/c')<br>
root #=> 'a'<br>
path #=> 'b/c'<br>
=end</p> Ruby master - Feature #6648 (Assigned): Provide a standard API for retrieving all command-line fl...https://bugs.ruby-lang.org/issues/66482012-06-26T07:56:37Zheadius (Charles Nutter)headius@headius.com
<p>=begin<br>
Currently there are no standard mechanisms to get the flags passed to the currently running Ruby implementation. The available mechanisms are not ideal:</p>
<ul>
<li>Scanning globals and hoping they have not been tweaked to new settings</li>
<li>Using external wrappers to launch Ruby</li>
<li>???</li>
</ul>
<p>Inability to get the full set of command-line flags, including flags passed to the VM itself (and probably VM-specific) makes it impossible to launch subprocess Ruby instances with the same settings.</p>
<p>A real world example of this is "((%bundle exec%))" when called with a command line that sets various flags, a la ((%jruby -Xsome.vm.setting --1.9 -S bundle exec%)). None of these flags can propagate to the subprocess, so odd behaviors result. The only option is to put the flags into an env var (((|JRUBY_OPTS|)) or ((|RUBYOPT|))) but this breaks the flow of calling a simple command line.</p>
<p>JRuby provides mechanisms to get all its command line options, but they require calling Java APIs from Ruby's API set. Rubinius provides its own API for accessing comand-line options, but I do not know if it includes VM-level flags as well as standard Ruby flags.</p>
<p>I know there is a (({RubyVM})) namespace in the 2.0 line. If that namespace is intended to be general-purpose for VM-level features, it would be a good host for this API. Something like...</p>
<p>class << RubyVM<br>
def vm_args; end # returns array of command line args <em>not</em> passed to the target script</p>
<pre><code>def script; end # returns the script being executed...though this overlaps with $0
def script_args; end # returns args passed to the script...though this overlaps with ARGV, but that is perhaps warranted since ARGV can be modified (i.e. you probably want the original args)
</code></pre>
<p>end<br>
=end</p> Ruby master - Feature #6641 (Open): Hash.auto constructorhttps://bugs.ruby-lang.org/issues/66412012-06-25T09:34:06Ztrans (Thomas Sawyer)
<p>=begin<br>
It is not uncommon to need a Hash following the pattern:</p>
<p>Hash.new{ |h,k| h[k]={} }</p>
<p>Another common example:</p>
<p>Hash.new{ |h,k| h[k]=[] }</p>
<p>This is common enough that it would very nice if we could have a more concise form, e.g.</p>
<p>Hash.auto{ {} }</p>
<p>Or for the second example:</p>
<p>Hash.auto{ [] }</p>
<p>Pure Ruby implementation is pretty simple:</p>
<p>def Hash.auto<br>
Hash.new{ |h,k| h[k] = yield }<br>
end</p>
<p>I think it would be nice to have in Core.</p>
<p>This is secondary, but it just occurred to me. Could there even be a literal notation for the above? Something like:</p>
<p>{}([])</p>
<p>?<br>
=end</p> Ruby master - Feature #6613 (Assigned): VT_RECORD, IRecordInfo Support in WIN32OLEhttps://bugs.ruby-lang.org/issues/66132012-06-21T07:54:17Zdsisnero (Dominic Sisneros)dsisnero@gmail.com
<p>WIN32OLE has no support for VT_RECORD VARIANTS. Python and Perl use the<br>
functions GetRecordInfoFromTypeInfo and GetRecordInfoFromGuids to add<br>
support for VT_RECORD and the IRecordInfo interface.</p>
<p>suggest having a class IRecordInfo and support for generating a Class<br>
for the UDT to use this Record/Struct in ruby</p>
<p>The method starting on 1395 needs a case statement for VT_RECORD and a way to turn that into a IRECORD class</p>
<p>static void *<br>
get_ptr_of_variant(VARIANT *pvar)<br>
{<br>
switch(V_VT(pvar)) {<br>
case VT_UI1:<br>
return &V_UI1(pvar);<br>
break;</p>
<p>The IDL definitions for the methods are as follows</p>
<p>HRESULT GetRecordInfoFromTypeInfo(<br>
__in ITypeInfo *pTypeInfo,<br>
__out IRecordInfo **ppRecInfo<br>
);</p>
<p>HRESULT GetRecordInfoFromGuids(<br>
__in REFGUID rGuidTypeLib,<br>
__in ULONG uVerMajor,<br>
__in ULONG uVerMinor,<br>
__in LCID lcid,<br>
__in REFGUID rGuidTypeInfo,<br>
__out IRecordInfo **ppRecInfo<br>
);</p>
<p>here is the CTYPES definition for python that adds this support</p>
<p>class IRecordInfo(IUnknown):<br>
# C:/vc98/include/OAIDL.H 5974<br>
<em>iid</em> = GUID("{0000002F-0000-0000-C000-000000000046}")</p>
<pre><code>def GetFieldNames(self, *args):
count = c_ulong()
self.__com_GetFieldNames(count, None)
array = (BSTR * count.value)()
self.__com_GetFieldNames(count, array)
result = array[:]
# XXX Should SysFreeString the array contents. How to?
return result
</code></pre>
<p>IRecordInfo. <em>methods</em> = [<br>
COMMETHOD([], HRESULT, 'RecordInit',<br>
(['in'], c_void_p, 'pvNew')),<br>
COMMETHOD([], HRESULT, 'RecordClear',<br>
(['in'], c_void_p, 'pvExisting')),<br>
COMMETHOD([], HRESULT, 'RecordCopy',<br>
(['in'], c_void_p, 'pvExisting'),<br>
(['in'], c_void_p, 'pvNew')),<br>
COMMETHOD([], HRESULT, 'GetGuid',<br>
(['out'], POINTER(GUID), 'pguid')),<br>
COMMETHOD([], HRESULT, 'GetName',<br>
(['out'], POINTER(BSTR), 'pbstrName')),<br>
COMMETHOD([], HRESULT, 'GetSize',<br>
(['out'], POINTER(c_ulong), 'pcbSize')),<br>
COMMETHOD([], HRESULT, 'GetTypeInfo',<br>
(['out'], POINTER(POINTER(ITypeInfo)), 'ppTypeInfo')),<br>
COMMETHOD([], HRESULT, 'GetField',<br>
(['in'], c_void_p, 'pvData'),<br>
(['in'], c_wchar_p, 'szFieldName'),<br>
(['out'], POINTER(VARIANT), 'pvarField')),<br>
COMMETHOD([], HRESULT, 'GetFieldNoCopy',<br>
(['in'], c_void_p, 'pvData'),<br>
(['in'], c_wchar_p, 'szFieldName'),<br>
(['out'], POINTER(VARIANT), 'pvarField'),<br>
(['out'], POINTER(c_void_p), 'ppvDataCArray')),<br>
COMMETHOD([], HRESULT, 'PutField',<br>
(['in'], c_ulong, 'wFlags'),<br>
(['in'], c_void_p, 'pvData'),<br>
(['in'], c_wchar_p, 'szFieldName'),<br>
(['in'], POINTER(VARIANT), 'pvarField')),<br>
COMMETHOD([], HRESULT, 'PutFieldNoCopy',<br>
(['in'], c_ulong, 'wFlags'),<br>
(['in'], c_void_p, 'pvData'),<br>
(['in'], c_wchar_p, 'szFieldName'),<br>
(['in'], POINTER(VARIANT), 'pvarField')),<br>
COMMETHOD([], HRESULT, 'GetFieldNames',<br>
(['in', 'out'], POINTER(c_ulong), 'pcNames'),<br>
(['in'], POINTER(BSTR), 'rgBstrNames')),<br>
COMMETHOD([], BOOL, 'IsMatchingType',<br>
(['in'], POINTER(IRecordInfo))),<br>
COMMETHOD([], HRESULT, 'RecordCreate'),<br>
COMMETHOD([], HRESULT, 'RecordCreateCopy',<br>
(['in'], c_void_p, 'pvSource'),<br>
(['out'], POINTER(c_void_p), 'ppvDest')),<br>
COMMETHOD([], HRESULT, 'RecordDestroy',<br>
(['in'], c_void_p, 'pvRecord'))]</p>
<p>################################################################</p>
<a name="functions"></a>
<h1 >functions<a href="#functions" class="wiki-anchor">¶</a></h1>
<p>_oleaut32 = oledll.oleaut32</p>
<p>def GetRecordInfoFromTypeInfo(tinfo):<br>
"Return an IRecordInfo pointer to the UDT described in tinfo"<br>
ri = POINTER(IRecordInfo)()<br>
_oleaut32.GetRecordInfoFromTypeInfo(tinfo, byref(ri))<br>
return ri</p>
<p>def GetRecordInfoFromGuids(rGuidTypeLib, verMajor, verMinor, lcid,<br>
rGuidTypeInfo):<br>
ri = POINTER(IRecordInfo)()<br>
_oleaut32.GetRecordInfoFromGuids(byref(GUID(rGuidTypeLib)),<br>
verMajor, verMinor, lcid,<br>
byref(GUID(rGuidTypeInfo)),<br>
byref(ri))<br>
return ri</p> Ruby master - Feature #6611 (Assigned): Comments requested on implementation of set_parse_funchttps://bugs.ruby-lang.org/issues/66112012-06-20T07:46:26Zcjheath (Clifford Heath)clifford.heath@gmail.com
<p>Folk,</p>
<p>I've implemented Twister, a new mutation testing tool to replace Heckle.<br>
It relies on a new hook into the Ruby parser, in order to modify what the<br>
parser thinks it has seen.</p>
<p>Although I have written C extensions before, there are some aspects of<br>
the Ruby core which I'm unfamiliar with and as a result don't know the right<br>
way to handle. I'd like your comments, suggestions and improvements<br>
please.</p>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db</a></p>
<p>In particular, I'd like to know the following:</p>
<ol>
<li>Do you prefer that I move the literal strings (which occur once each) to #defined?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R1003" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R1003</a></p>
<ol start="2">
<li>Will this line of code mess up the GC, and how should I fix that?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R3853" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R3853</a></p>
<ol start="3">
<li>The set_parse_func is extern though it should be static, but I need to move<br>
the rb_define_global_function out of thread.c. Can someone please tell me where I should<br>
move it to, since there is no Init_Parser?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R9029" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R9029</a></p>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L3R4705" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L3R4705</a></p>
<ol start="4">
<li>I think I should change set_parse_func to accept a flags argument and a block,<br>
instead of assuming all flags, and taking a Proc. What are the downsides of using a<br>
block instead of a Proc (does this reduce the number of Bindings that get created)?<br>
How do I change set_parse_func to use a block?</li>
</ol>
<p>The initial implementation of Twister is an extension to RSpec which adds the option<br>
"--twist file-or-dir". It's still a bit rough - it needs to change the reporting on the twisted<br>
runs that follow the first (untwisted) run - but it does prove then concept.</p>
<p>Clifford Heath, Data Constellation, <a href="http://dataconstellation.com" class="external">http://dataconstellation.com</a><br>
Agile Information Management and Design.</p> Ruby master - Feature #6596 (Assigned): New method `Array#indexes`https://bugs.ruby-lang.org/issues/65962012-06-15T18:05:05Zrobin850 (Robin Dupret)robin.dupret@gmail.com
<p>I submitted a pull request on Github that provides a new method <code>Array#indexes</code>. It departs from <code>Array#index</code> in such a way that it returns an array of indexes and not the single first occurrence that is relevant.</p>
<p>The reason I want this method is that I don't understand why <code>Array#index</code> returns a single index if the parameter is in the array several times.</p>
<p>Examples</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="n">a</span><span class="p">.</span><span class="nf">indexes</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1">#=> [0, 3]</span>
<span class="n">a</span><span class="p">.</span><span class="nf">index</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => 0</span>
</code></pre>
<p>In my opinion, it's not logical to return only a single index since <code>1</code> is in the array twice.</p> Ruby master - Feature #6594 (Assigned): Integrated Functorhttps://bugs.ruby-lang.org/issues/65942012-06-15T09:02:38Ztrans (Thomas Sawyer)
<p>I know the developers meeting is coming up so I'd like to get a few ideas I've had sitting in the wings out in the air before then.</p>
<p>One the more useful is the idea of integrating Functors directly into the language. "Functor" is the term I use for "higher-order function".</p>
<p>I blogged about this idea and you can read it here: <a href="http://trans.github.com/2011-09-07-ruby-heart-higher-order-functions/" class="external">http://trans.github.com/2011-09-07-ruby-heart-higher-order-functions/</a></p>
<p>The super short version is this:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">def</span> <span class="nf">f</span> <span class="o">=></span> <span class="n">op</span><span class="p">,</span> <span class="n">arg</span>
<span class="n">arg</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="n">__op__</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
<span class="k">end</span>
<span class="n">f</span> <span class="o">+</span> <span class="mi">3</span> <span class="c1">#=> 6</span>
<span class="n">f</span> <span class="o">*</span> <span class="mi">3</span> <span class="c1">#=> 9</span>
</code></pre>
<p>Another example:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">class</span> <span class="nc">String</span>
<span class="k">def</span> <span class="nf">file</span> <span class="o">=></span> <span class="n">op</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span>
<span class="no">File</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="n">__op__</span><span class="p">,</span> <span class="nb">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="s2">"README.rdoc"</span><span class="p">.</span><span class="nf">file</span><span class="p">.</span><span class="nf">mtime</span> <span class="c1">#=> 2012-06-14 12:34:45 -0400</span>
</code></pre>
<p>I'm using <code>=></code> as means of indicating a higher-order function. Of course another syntax could be used if this won't fly. The important thing is the idea of higher-order functions being integrated directly into the language. Doing this without that integration requires the creation of an intermediate object for each call which is very inefficient.</p> Ruby master - Feature #6452 (Assigned): Allow extend to override class methodshttps://bugs.ruby-lang.org/issues/64522012-05-19T01:58:25Zrosenfeld (Rodrigo Rosenfeld Rosas)rr.rosas@gmail.com
<pre><code>module A
def self.a
'a1'
end
end
module B
def a
'a2'
end
def b
'b'
end
end
A.extend B
assert A.a == 'a2' # this is the change I'm proposing - currently it is 'a1'
assert A.b == 'b'
</code></pre>
<p>Would this change be possible for 3.0?</p> Ruby master - Feature #6445 (Assigned): request for default length/position on string indexhttps://bugs.ruby-lang.org/issues/64452012-05-17T13:02:30Zbotp (bot pena)botpena@gmail.com
<p>would be nice if ruby has default for "rest or up to end of string"</p>
<p>eg</p>
<p>"hello"[2,] => should default to "hello"[2..-1]<br>
or<br>
"hello"[2..] => should default to "hello"[2..-1]</p> Ruby master - Feature #6413 (Assigned): Make Dir.entries default to Dir.entries(Dir.pwd)https://bugs.ruby-lang.org/issues/64132012-05-08T22:12:34Zshevegen (Robert A. Heiler)shevegen@gmail.com
<p>Is there a reason why Dir.entries requires one argument?</p>
<p>I think it would be easier and more convenient for the userruby if it would default to the current directory. Like so:</p>
<p>Dir.entries(i = Dir.pwd)</p>
<p>Or is there a reason why this is not done?</p> Ruby master - Feature #6376 (Assigned): Feature lookup and checking if feature is loadedhttps://bugs.ruby-lang.org/issues/63762012-04-29T07:03:40Ztrans (Thomas Sawyer)
<p>$LOADED_FEATURES is useful to know what "files" have been loaded. But it doesn't really tell us what "features" have been loaded. If there where were a way to look-up a load path, without actually loading it then it would be possible to compare that to $LOADED_FEATURES and thus know. e.g.</p>
<pre><code>require 'ostruct'
$LOADED_FEATURES #=> [..., "/home/trans/.local/lib/ry/rubies/1.9.3-p125/lib/ruby/1.9.1/ostruct.rb"]
path = require_path('ostruct') #=> "/home/trans/.local/lib/ry/rubies/1.9.3-p125/lib/ruby/1.9.1/ostruct.rb"
$LOADED_FEATURES.include?(path)
</code></pre>
<p>Of course, it would be nice to also have:</p>
<pre><code>required?('ostruct') #=> true
</code></pre>
<p>These methods could be class methods of special module, if it's important to keep the Kernel more tidy, e.g. <code>Ruby.required?('ostruct')</code>.</p>
<p>I am currently working on a project where I need this (and have a couple of other projects that could use it too) and I've had to implement the whole thing from scratch, which isn't simple, nor fast, nor am I 100% confident that it specs exactly to Ruby's own lookup procedure. So it would be much better if Ruby would expose its lookup functionality.</p> Ruby master - Bug #6360 (Assigned): Debug information build even without requesting ithttps://bugs.ruby-lang.org/issues/63602012-04-26T08:46:44Zluislavena (Luis Lavena)luislavena@gmail.com
<p>Hello,</p>
<p>While working on latest RubyInstaller release for 1.9.3-p194 our team detected a bigger shared library and import library being generated.</p>
<p>After further inspection, we found this commit:<br>
<a href="https://github.com/ruby/ruby/commit/ffdaca1d748804f2b5ca2de612f17cf6c78d351b" class="external">https://github.com/ruby/ruby/commit/ffdaca1d748804f2b5ca2de612f17cf6c78d351b</a></p>
<p>Backported r34840 into ruby_1_9_3 branch</p>
<p>The above change added -ggdb to CFLAGS even when was not provided by debugflags configure option.</p>
<p>The following is the comparison of "make" summary with and without the change:</p>
<p>Current trunk:</p>
<pre>
C:\Users\Luis\Projects\oss\ruby\build32>make
CC = gcc
LD = ld
LDSHARED = gcc -shared
CFLAGS = -O3 -fno-omit-frame-pointer -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Werror=pointer-arith -Werror=write-strings -Werror=declaration-after-statement -Werror=implicit-function-declaration
XCFLAGS = -include ruby/config.h -include ruby/missing.h -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fvisibility=hidden -DRUBY_EXPORT
CPPFLAGS = -DFD_SETSIZE=32767 -D_WIN32_WINNT=0x0501 -I. -I.ext/include/i386-mingw32 -I../include -I..
DLDFLAGS = -Wl,--enable-auto-image-base,--enable-auto-import -Wl,--out-implib=libmsvcrt-ruby200.dll.a msvcrt-ruby200.def -Wl,--stack,0x00200000,--enable-auto-import
SOLIBS = msvcrt-ruby200.res.o -lshell32 -lws2_32 -limagehlp
</pre>
<p>Reverting r34840:</p>
<pre>
C:\Users\Luis\Projects\oss\ruby\build32>make
CC = gcc
LD = ld
LDSHARED = gcc -shared -s
CFLAGS = -O3 -fno-omit-frame-pointer -g -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Werror=pointer-arith -Werror=write-strings -Werror=declaration-after-statement -Werror=implicit-function-declaration
XCFLAGS = -include ruby/config.h -include ruby/missing.h -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fvisibility=hidden -DRUBY_EXPORT
CPPFLAGS = -DFD_SETSIZE=32767 -D_WIN32_WINNT=0x0501 -I. -I.ext/include/i386-mingw32 -I../include -I..
DLDFLAGS = -Wl,--enable-auto-image-base,--enable-auto-import -Wl,--out-implib=libmsvcrt-ruby200.dll.a msvcrt-ruby200.def -Wl,--stack,0x00200000,--enable-auto-import
SOLIBS = msvcrt-ruby200.res.o -lshell32 -lws2_32 -limagehlp
</pre>
<p>Notice that -g changed into -ggdb instead.</p>
<p>I think debug symbols shouldn't be compiled unless requested and this is a regression.</p> Ruby master - Feature #6354 (Assigned): Remove escape (break/return/redo/next support) from class...https://bugs.ruby-lang.org/issues/63542012-04-25T12:12:17Zko1 (Koichi Sasada)
<p>Let's remove global escape (break/return/redo/next support) from class/module scope.</p>
<p>Yes, it introduces incompatibility. However, anyone use it?<br>
I think the following examples are evil (difficult to understand).</p>
<a name="examples"></a>
<h1 >examples:<a href="#examples" class="wiki-anchor">¶</a></h1>
<p>1.times{<br>
class C<br>
break # break from 1.times<br>
end<br>
}</p>
<p>1.times{<br>
class C<br>
module M<br>
break # break from 1.times<br>
end<br>
end<br>
}</p>
<p>3.times{|n|<br>
p n # repeat print 0<br>
class C<br>
redo<br>
end<br>
}</p>
<p>->{<br>
class C<br>
return return from outer lambda block<br>
end<br>
}.call</p>
<p>->{<br>
proc{<br>
class C<br>
return # return from outer lambda (not proc) block<br>
end<br>
}.call<br>
}.call</p>
<p>etc, etc.</p> Ruby master - Bug #6351 (Assigned): transcode table generator does not support multi characters o...https://bugs.ruby-lang.org/issues/63512012-04-24T20:41:39Zusa (Usaku NAKAMURA)usa@garbagecollect.jp
<p>改めてチケット起こします。<a href="/issues/6349">[ruby-dev:45576]</a> より。</p>
<p>On 2012/04/24 17:11, "Martin J. Dürst" wrote:</p>
<blockquote>
<p>On 2012/04/24 17:02, U.Nakamura wrote:</p>
<blockquote>
<p>データは例によってNetBSDのものが利用できそうです。<br>
なのですが、transcodeってUnicodeの第0面(BMP)以外はサポートし<br>
てましたっけ?</p>
</blockquote>
<p>もちろんです :-)</p>
</blockquote>
<p>もうちょっと調べました。BMP 以外は transcode の最初から全く問題ないです<br>
が、現時点で引っかかるのは次のものです<br>
(<a href="http://x0213.org/codetable/euc-jis-2004-std.txt" class="external">http://x0213.org/codetable/euc-jis-2004-std.txt</a> から抜粋):</p>
<p>0xA4F7 U+304B+309A # [2000]<br>
0xA4F8 U+304D+309A # [2000]<br>
0xA4F9 U+304F+309A # [2000]<br>
0xA4FA U+3051+309A # [2000]<br>
0xA4FB U+3053+309A # [2000]</p>
<p>0xA5F7 U+30AB+309A # [2000]<br>
0xA5F8 U+30AD+309A # [2000]<br>
0xA5F9 U+30AF+309A # [2000]<br>
0xA5FA U+30B1+309A # [2000]<br>
0xA5FB U+30B3+309A # [2000]<br>
0xA5FC U+30BB+309A # [2000]<br>
0xA5FD U+30C4+309A # [2000]<br>
0xA5FE U+30C8+309A # [2000]</p>
<p>0xA6F8 U+31F7+309A # [2000]</p>
<p>0xABC4 U+00E6+0300 # [2000]</p>
<p>0xABC8 U+0254+0300 # [2000]<br>
0xABC9 U+0254+0301 # [2000]<br>
0xABCA U+028C+0300 # [2000]<br>
0xABCB U+028C+0301 # [2000]<br>
0xABCC U+0259+0300 # [2000]<br>
0xABCD U+0259+0301 # [2000]<br>
0xABCE U+025A+0300 # [2000]<br>
0xABCF U+025A+0301 # [2000]</p>
<p>0xABE5 U+02E9+02E5 # [2000]<br>
0xABE6 U+02E5+02E9 # [2000]</p>
<p>ようするに、JIS X 0213 で一文字になっているが、Unicode で二文字になって<br>
いるものです。EUC-JISX0213 から UTF-8 は問題ないですが、逆は現在引っかか<br>
ります。windows-1258 も (逆ですが) 同じ問題がありますので、いずれはなく<br>
さないといけないと思いましたが、今回はいいきっかけのではないかと思います。</p>
<p>よろしくお願いします。 Martin.</p> Ruby master - Feature #6337 (Assigned): FileUtils#synchttps://bugs.ruby-lang.org/issues/63372012-04-22T09:13:25Ztrans (Thomas Sawyer)
<p>=begin<br>
I'd like to see some sort of FileUtils#sync method to sync the contents of one directory with another.</p>
<p>Here is a prototype definition:</p>
<pre><code>#
# Synchronize a destination directory with a source directory.
#
def sync(src, dst, options={})
src_files = Dir[File.join(src, '**', '*')].map{ |f| f.sub(src+'/', '') }
dst_files = Dir[File.join(dst, '**', '*')].map{ |f| f.sub(dst+'/', '') }
removal = dst_files - src_files
rm_dirs, rm_files = [], []
removal.each do |f|
path = File.join(dst, f)
if File.directory?(path)
rm_dirs << path
else
rm_files << path
end
end
rm_files.each { |f| rm(f) }
rm_dirs.each { |d| rmdir(d) }
src_files.each do |f|
src_path = File.join(src, f)
dst_path = File.join(dst, f)
if File.directory?(src_path)
mkdir_p(dst_path)
else
parent = File.dirname(dst_path)
mkdir_p(parent) unless File.directory?(parent)
install(src_path, dst_path)
end
end
end
</code></pre>
<p>I haven't tested this beyond a simple trial. It needs improvement. For one, it probably should be able to handle regular files as arguments too. It also needs to handle verbose and dryrun options properly. Nonetheless, with improvements, would be okay for such to become new feature for FileUtils?</p>
<p>=end</p> Ruby master - Feature #6317 (Assigned): Range#cover?の引数としてRangeインスタンスを受けられるようにして欲しいhttps://bugs.ruby-lang.org/issues/63172012-04-18T20:51:08Zmasaakiaoyagi (Masaaki Aoyagi)masaaki.aoyagi@gmail.com
<p>青柳と申します。</p>
<p>以下のように、Range#cover?の引数としてRangeインスタンスを<br>
受けられるようにして欲しいです。<br>
(1..4).cover?(2..3) # => true<br>
(1..4).cover?(0..3) # => false</p>
<p>取り敢えず実装してみましたので、添付いたします。</p> Ruby master - Feature #6309 (Assigned): Add a reference queue for weak referenceshttps://bugs.ruby-lang.org/issues/63092012-04-17T17:10:15Zheadius (Charles Nutter)headius@headius.com
<p>Most interesting uses of WeakRef are much harder to do efficiently without a reference queue.</p>
<p>A reference queue, as implemented by the JVM, is basically a queue into which weak references are placed some time after the object they refer to has been collected. The queue can be polled cheaply to look for collected references.</p>
<p>A simple example of usage can be seen in the weakling gem, with an efficient implementation of an ID hash: <a href="https://github.com/headius/weakling/blob/master/lib/weakling/collections.rb" class="external">https://github.com/headius/weakling/blob/master/lib/weakling/collections.rb</a></p>
<p>Notice the _cleanup method is called for every operation, to keep the hash clear of dead references. Failure to have a _cleanup method would mean the hash grows without bounds.</p>
<p>_cleanup cannot be implemented efficiently on MRI at present because there's no reference queue implementation. On MRI, _cleanup would have to perform a linear scan of all stored values periodically to search for dead references. For a heavily used hash with many live values, this becomes a very expensive operation.</p>
<p>It's probably possible to implement reference queues efficiently atop the new ObjectSpace::WeakMap internals, since it already keeps track of weak references and can run code when a weak reference no longer refers to a live object.</p> Ruby master - Feature #6308 (Assigned): Eliminate delegation from WeakRefhttps://bugs.ruby-lang.org/issues/63082012-04-17T17:02:28Zheadius (Charles Nutter)headius@headius.com
<p>WeakRef's delegation features are a really awful pattern that should not be allowed in future versions of Ruby.</p>
<p>WeakRef makes no guarantees as to the liveness of its contained object. It can be collected at any time if there are no strong references to it.</p>
<p>WeakRef currently uses delegation to pass method calls through to the contained object. This encourages a pattern where a WeakRef is passed to methods that expect to have a reference to the underlying object, making it appear to be that object.</p>
<p>Unfortunately, this is <em>never</em> a good idea. Because the object can be collected at any time, you may get a nil reference from <strong>getobj</strong> <em>arbitrarily</em> in code that tries to call methods against the given WeakRef. That means using WeakRef as a delegate will always result in unreliable code, and errors may happen for inexplicable reasons.</p>
<p>I believe Ruby 2.0 should eliminate WeakRef's delegation features and make it a simple reference holder. There's no safe way to use a weak reference except to grab a reference to the object, check that it is alive (non-nil) and then proceed with the use of the object, as follows:</p>
<p>obj = weakref.<strong>getobj</strong><br>
raise AppropriateError unless obj<br>
obj.do_something<br>
obj.do_something_else</p>
<p>Along with eliminating delegation, I would recommend simply making the get method #get, since the uglier #<strong>getobj</strong> is only named that way because it is not delegated.</p> Ruby master - Feature #6293 (Assigned): new queue / blocking queueshttps://bugs.ruby-lang.org/issues/62932012-04-14T08:28:58Ztenderlovemaking (Aaron Patterson)tenderlove@ruby-lang.org
<p>Hi,</p>
<p>I'd like to add new Queue objects to ruby. Whenever I use queues, I either use them in a blocking or non-blocking manner only, so I have separated them in to two classes Thread::Queue, and Thread::BlockingQueue.</p>
<p>Other notable differences, these queues:</p>
<ul>
<li>implement <code>poll</code>, which will return a nil if the queue is empty</li>
<li>do not allow <code>nil</code> to be in the queue as it would interfere with <code>poll</code>
</li>
<li>include Enumerable</li>
</ul>
<p>I think these will be a good basis for implementing a Deque, SynchronizedQueue, and PriorityQueue.</p>
<p>I've attached a patch against trunk.</p> Ruby master - Feature #6277 (Assigned): Hash#convert_keyhttps://bugs.ruby-lang.org/issues/62772012-04-11T01:12:20Ztrans (Thomas Sawyer)
<p>=begin<br>
Many times a hash with uniform keys is needed (or is at least preferable) for a particular usecase. To this end I propose ((%Hash#convert_key%)).</p>
<p>h = {}<br>
h.convert_key{ |k| k.to_sym }<br>
h['a'] = 1<br>
h.update('b'=>2)<br>
h #=> {:a=>1, :b=>2}</p>
<p>The idea is similar in concept to ((%#default_proc%)).</p>
<p>Others solutions to fill this need have been tried and used, but almost exclusively are in the form of a new class. Most notable is Rails HashWithIndifferentAccess. But ((%#convert_key%)) has much greater flexibility since keys can be converted to anything.<br>
=end</p> Ruby master - Feature #6265 (Assigned): Remove 'useless' 'concatenation' syntaxhttps://bugs.ruby-lang.org/issues/62652012-04-06T21:53:53Zrosenfeld (Rodrigo Rosenfeld Rosas)rr.rosas@gmail.com
<p>What is wrong with this code:</p>
<p>some_method 'argument1', 'argument2' 'argument3'</p>
<p>Yes, the missing colon, but it is not always easy to notice that...</p>
<p>What is this ('concatenation' 'syntax') useful for?</p>
<p>Why writing ('some ' 'concatenation') instead of 'some concatenation'?</p>
<p>A missing colon between string arguments can lead to some bugs that may be hard to find, specially if the arguments are optional.</p>
<p>And I can't see any useful case where this allowed syntax for concatenation would help.</p> Ruby master - Feature #6133 (Assigned): SSLSocketをshutdownできないhttps://bugs.ruby-lang.org/issues/61332012-03-13T00:17:22Zkik (Masashi Kikuchi)kik314@gmail.com
<p><a href="http://www.openssl.org/docs/ssl/SSL_shutdown.html" class="external">http://www.openssl.org/docs/ssl/SSL_shutdown.html</a><br>
に対応するメソッドがないので、送信の終わりを送れません。ただし微妙にshutdown(2)とインターフェースが違ってます。</p> Ruby master - Feature #6012 (Assigned): Proc#source_location also return the columnhttps://bugs.ruby-lang.org/issues/60122012-02-14T09:17:30Zrogerdpack (Roger Pack)rogerpack2005@gmail.com
<p>As originally suggested in <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/42418" class="external">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/42418</a></p>
<p>Suggestion/feature request:<br>
have #source_location also return the beginning column where it was defined.<br>
["test.rb", 8, 33]</p>
<p>Thanks!<br>
-roger-</p> Ruby master - Feature #5970 (Assigned): Add Enumerable#join with same semantics as Array#joinhttps://bugs.ruby-lang.org/issues/59702012-02-05T17:27:39Znow (Nikolai Weibull)now@disu.se
<p>Currently, to join the elements of an Enumerable, you need to call #to_a on the Enumerable and then #join the result. With Enumerable#join one wouldn’t need need to create an intermediate Array.</p> Ruby master - Feature #5945 (Assigned): Add the ability to mark a at_exit as process-local. https://bugs.ruby-lang.org/issues/59452012-01-30T09:59:36Zrobertgleeson (Robert Gleeson)
<p>I'd like to propose a enhancement to <code>at_exit</code>.<br>
It would be nice if you could stop a <code>at_exit</code> handler from running in subprocesses.<br>
You can do this manually with this code:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">parent</span> <span class="o">=</span> <span class="no">Process</span><span class="p">.</span><span class="nf">pid</span>
<span class="nb">at_exit</span> <span class="k">do</span>
<span class="k">if</span> <span class="n">parent</span> <span class="o">==</span> <span class="no">Process</span><span class="p">.</span><span class="nf">pid</span>
<span class="c1"># …</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>You can also do it by bypassing handlers:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">at_exit</span> <span class="k">do</span>
<span class="c1"># …</span>
<span class="k">end</span>
<span class="nb">fork</span> <span class="k">do</span>
<span class="nb">exit!</span>
<span class="k">end</span>
</code></pre>
<p>But it would be nice if I could do:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">at_exit</span><span class="p">(</span><span class="kp">false</span><span class="p">)</span> <span class="k">do</span>
<span class="c1"># …</span>
<span class="k">end</span>
</code></pre>
<p>The first approach is kind of ugly, and the second approach isn't sustainable if code outside<br>
your control can <code>fork(…)</code> without calling <code>exit!</code>.</p> Ruby master - Feature #5825 (Assigned): Sweet instance var assignment in the object initializerhttps://bugs.ruby-lang.org/issues/58252011-12-30T22:49:03Zgoshakkk (Gosha Arinich)me@goshakkk.name
<p>I'm very excited about this feature in CoffeeScript, and think it might be a nice-to-have thing in Ruby 2.0.</p>
<p>That's how I think it would look like:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">class</span> <span class="nc">Me</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="vi">@name</span><span class="p">,</span> <span class="vi">@age</span><span class="p">,</span> <span class="vi">@location</span><span class="p">);</span> <span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>So we can declare <code>@variable</code>s in the initializer method parameters definition to avoid assigning instance variables from method arguments by hand, like:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">class</span> <span class="nc">Me</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">age</span><span class="p">,</span> <span class="n">location</span><span class="p">)</span>
<span class="vi">@name</span> <span class="o">=</span> <span class="nb">name</span>
<span class="vi">@age</span> <span class="o">=</span> <span class="n">age</span>
<span class="vi">@location</span> <span class="o">=</span> <span class="n">location</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>Want to hear what do you guys think, does that feature worth being included in 2.0?</p> Ruby master - Feature #5781 (Assigned): Query attributes (attribute methods ending in `?` mark)https://bugs.ruby-lang.org/issues/57812011-12-20T04:57:11Ztrans (Thomas Sawyer)
<p>Pretty sure this has come up before, but I'd like to revisit b/c I don't understand why it isn't allowed.</p>
<p>Sometimes I define "query" attributes, and in those cases I'd like the reader method to end in a <code>?</code> mark. Currently I have to do:</p>
<pre><code># @attribute
def foo?
@foo
end
</code></pre>
<p>or, if I don't mind a shadowing bare method,</p>
<pre><code>attr :foo
alias_method :foo?, :foo
</code></pre>
<p>So why not just allow:</p>
<pre><code>attr :foo?
</code></pre>
<p>Currently this causes an error. But why? It just seems like a waste of potentially cleaner code.</p> Ruby master - Feature #5764 (Assigned): Net::HTTP should assume HTTP/0.9 on unexpected responseshttps://bugs.ruby-lang.org/issues/57642011-12-15T06:01:34Zmstyer (Mike Styer)michael@styer.net
<p>Currently Net::HTTP.read_status_line throws Net::HTTPBadResponse if the status line does not conform to HTTP/1.1 specifications.</p>
<p>But in cases when the web server implements a request size limit, it may not read HTTP/1.1 trailer after the request URI and may send back an HTTP/0.9 response.</p>
<p>Nginx does this for 414 Request-URI Too Large responses:</p>
<p><a href="http://lxr.evanmiller.org/http/source/http/ngx_http_header_filter_module.c#L95" class="external">http://lxr.evanmiller.org/http/source/http/ngx_http_header_filter_module.c#L95</a><br>
<a href="http://forum.nginx.org/read.php?2,52862,52862" class="external">http://forum.nginx.org/read.php?2,52862,52862</a></p>
<p>Perl's Net::HTTP provides a "laxed" option to read_response_headers() to assume HTTP/0.9 if it can't find an HTTP/1.1 status line. Ruby should provide a similar option.</p> Ruby master - Feature #5749 (Assigned): new method String#match_all neededhttps://bugs.ruby-lang.org/issues/57492011-12-12T18:03:57Zyimutang (Joey Zhou)
<p>The String class should contain an instance method 'match_all', which is a mixture of 'match' and 'scan'.</p>
<p>The method 'scan' is not a very powerful tool, its result(the yielding thing) is just a matched string or an array of captured strings.</p>
<p>p 'a1bc2de3f'.scan(/(.)\d(.)/) # [["a", "b"], ["c", "d"], ["e", "f"]]</p>
<p>If the regex argument contains groups, I even cannot get the whole matched string, and no information about the matched offsets.</p>
<p>So, a 'match_all' is very necessary. It scan the string, finding every matched, and yielding <em>MatchData instance</em> to the following block.</p>
<p>Here's a simple implemention in Ruby:</p>
<p>class String<br>
def match_all(re,i=0)<br>
if block_given?<br>
while m = self.match(re,i)<br>
yield m<br>
i = m.end(0)<br>
end<br>
return self<br>
else<br>
ary = []<br>
while m = self.match(re,i)<br>
ary << m<br>
i = m.end(0)<br>
end<br>
return ary<br>
end<br>
end<br>
end</p>
<p>However, it is not efficient in the 'while m = self.match(re,i)' way, because it scan the string again and again. If string is UTF8-encoded and contains out-of-ASCII characters, I'm afraid getting the start index of it is so expensive.</p>
<p>So, I think a built-in 'match_all' method, which behaves just like 'scan' but yield MatchData, is needed.</p>
<p>Please consider it, thank you!</p> Ruby master - Feature #5741 (Assigned): Secure Erasure of Passwordshttps://bugs.ruby-lang.org/issues/57412011-12-11T06:02:13ZMartinBosslet (Martin Bosslet)Martin.Bosslet@gmail.com
<p>In other languages it is considered good practice to securely erase<br>
passwords immediately after they were used. Imagine authentication<br>
in a web app - ultimately a String containing the password arrives<br>
at the server, where it will be processed and compared to some<br>
previously stored value. After this is done, there is no need to<br>
store these password Strings any longer, so they should be<br>
discarded right away (more on why later).</p>
<p>In C, you would simply overwrite the array of bytes with zeroes or<br>
random values. In Java, Strings are immutable, that's why there it<br>
is common practice to use char[] for all things password and overwrite<br>
them when done.</p>
<p>Currently, there is no way in Ruby to overwrite the memory that<br>
was used by a String. String#clear and String#replace both use<br>
str_discard internally, which only frees the underlying pointer<br>
without overwriting it.</p>
<p>The problem with not erasing passwords is this: the contents of the<br>
String stay in memory until they are finally GC'ed. But even then<br>
only the pointer will be freed, leaving the contents mostly intact<br>
until the memory is reclaimed and overwritten later on.</p>
<p>This could be exploited if an attacker had access to the memory of<br>
the server. This could happen in many ways: a core dump after a<br>
crash, access to the host if the server runs in a VM, or even by<br>
deep-freezing the DRAM :) [1]</p>
<p>It could be argued that given the examples above, much more<br>
devastating attacks would be possible since in all of those<br>
cases you more or less have physical access to the machine. But<br>
I would still consider this to be a valid concern, if not only<br>
for the reason of never opening additional attack surfaces if<br>
they can be avoided relatively easily.</p>
<p>I also found [2], which seems to show that Python deals with<br>
similar problems and it also contains more background info.</p>
<p>Eric Hodel and I discussed this yesterday and Eric came up with<br>
a C extension that can be used to illustrate the problem (attached).</p>
<p>If you inspect the resulting core dump, you will find the following:</p>
<ul>
<li>the untouched String remains in memory fully intact</li>
<li>the String#clear'ed String remains to a large extent, typically the<br>
first character is missing - so if you typed "PASSWORD", search for<br>
"ASSWORD" (unintentional pun) instead</li>
<li>The String#clear_secure'ed will have been completely erased, no<br>
traces remain</li>
</ul>
<p>My questions:</p>
<ol>
<li>Would you agree that we need this functionality?</li>
<li>Where would we ideally place it? I'm not sure whether<br>
String is the perfect place, but on the other hand, String<br>
is the only place where we have access to the implementation<br>
details.</li>
<li>Are there better alternative ways how we could achieve this?</li>
</ol>
<p>[1] <a href="http://www.schneier.com/blog/archives/2008/02/cold_boot_attac.html" class="external">http://www.schneier.com/blog/archives/2008/02/cold_boot_attac.html</a><br>
[2] <a href="http://stackoverflow.com/questions/728164/securely-erasing-password-in-memory-python" class="external">http://stackoverflow.com/questions/728164/securely-erasing-password-in-memory-python</a></p> Ruby master - Feature #5654 (Assigned): Introduce global lock to avoid concurrent requirehttps://bugs.ruby-lang.org/issues/56542011-11-21T19:51:02Znahi (Hiroshi Nakamura)nakahiro@gmail.com
<p>=begin<br>
Current implementation of "require" has locks for each file (expanded name from required feature) and serializes file loading from Threads. The first Thread acquires the lock for the file and starts loading. The second Thread waits for acquiring the lock, and when the first Thread release the lock, it acquires the lock, then returns immediately.<br>
This can cause deadlock by cross-require from Threads.</p>
<p>And code that does not properly use "require" could meet several problems;</p>
<ul>
<li>constants can be defined before they're ready for use</li>
<li>classes can be modified while they're being used</li>
<li>global state can be initialized at the same time it's in use</li>
</ul>
<p>Proposal: introduce global (per VM) lock to avoid concurrent file loading by "require" so that only one Thread can call "require" at the same time.</p>
<p>I don't have pros/cons list at this moment. Let's discuss it, too.</p>
<p>Derived from a discussion at <a class="issue tracker-4 status-6 priority-4 priority-default closed" title="Backport: Please backport thread-safe autoloading patch (Rejected)" href="https://bugs.ruby-lang.org/issues/5621">#5621</a> (thread-safe autoload)<br>
=end</p> Ruby master - Feature #5643 (Assigned): require/load options and binding optionhttps://bugs.ruby-lang.org/issues/56432011-11-17T07:41:01Ztrans (Thomas Sawyer)
<p>Current Kernel#load is defined as:</p>
<pre><code>load(filename, wrap=false)
</code></pre>
<p>I purpose that it be modified to work as option argument, e.g.</p>
<pre><code>load(filename, :wrap=>true)
</code></pre>
<p>Right off the bat this has better name connascence.</p>
<p>Then support an additional option <code>:binding</code>, such that, given:</p>
<pre><code>$ cat lib/example.rb
def a
1
end
</code></pre>
<p>then</p>
<pre><code>class X
load('example.rb', :binding=>binding)
end
X.new.a #=> 1
</code></pre>
<p>The binding option should also work with #require (which would also support option parameter) differing from #load in the it would only allow the feature to be loaded once per-binding's self regardless of being required again.</p>
<p>This ability would greatly benefit systems that need "plugin" capability. Presently, a great deal of coding has to go into simulating this functionality to create plugin systems, which are often imperfect nor robust.</p> Ruby master - Feature #5617 (Assigned): Allow install RubyGems into dediceted directoryhttps://bugs.ruby-lang.org/issues/56172011-11-11T22:12:09Zvo.x (Vit Ondruch)v.ondruch@tiscali.cz
<p>Hello,</p>
<p>I would like to propose my patch, which allows to optionally install RubyGems library into dedicated directory, out of the default Ruby directory structure. This should enable to easily share one RubyGems library by more Ruby implementations and avoids code duplication. I did this patch since Fedora prohibits duplication of system libraries [1], which would be the case if MRI and JRuby are installed in parallel.</p>
<p>Thank you for considering this patch.</p>
<p>Vit</p>
<p>[1] <a href="https://fedoraproject.org/wiki/Packaging:Guidelines#Duplication_of_system_libraries" class="external">https://fedoraproject.org/wiki/Packaging:Guidelines#Duplication_of_system_libraries</a></p> Ruby master - Feature #5582 (Assigned): Allow clone of singleton methods on a BasicObjecthttps://bugs.ruby-lang.org/issues/55822011-11-07T12:34:13Zthinkerbot (Simon Chiang)simon.a.chiang@gmail.com
<p>Currently I do not know of a way to implement something like 'clone' on a BasicObject subclass. This is as close as I've gotten but as you can see the singleton methods are not propagated to the clone.</p>
<pre><code>require 'test/unit'
class Context < BasicObject
def _singleton_class_
class << self
SINGLETON_CLASS = self
def _singleton_class_
SINGLETON_CLASS
end
end
_singleton_class_
end
def _class_
_singleton_class_.superclass
end
def _extend_(mod)
mod.__send__(:extend_object, self)
end
def _initialize_clone_(orig)
# set variables as needed
end
def _clone_
clone = _class_.allocate
clone._initialize_clone_(self)
_singleton_class_.included_modules.each {|mod| clone._extend_ mod }
clone
end
end
class ContextTest < Test::Unit::TestCase
module A
def a
:a
end
end
def test__clone__inherits_modules
context = Context.new
context._extend_ A
clone = context._clone_
assert_equal :a, clone.a
end
def test__clone__inherits_singleton_methods
context = Context.new
def context.a
:a
end
clone = context._clone_
assert_equal :a, clone.a # fails
end
end
</code></pre>
<p>Is there a way to do this that I don't see? If not, then I request that a way be added - perhaps by allowing the singleton_class to be set somehow.</p>
<p>In my case I am using Context as the context for a dsl where methods write to a target (an instance variable). I want to be able to clone a context such that I can have multiple contexts with the same methods, including extensions and singletons, that write to different targets.</p>
<p>Thank you.</p> Ruby master - Feature #5558 (Assigned): String#% strange arity errorshttps://bugs.ruby-lang.org/issues/55582011-11-03T10:25:55Ztrans (Thomas Sawyer)
<p>When the number of arguments do not match the number of % parameters, the String#% method has some odd behavior.</p>
<p>When too many, it seems to work fine, ignoring the extra arguments.</p>
<p>"%s" % [1,2] #=> "1"</p>
<p>But if <code>$DEBUG = true</code>,</p>
<p>"%s" % [1,2] #=> ArgumentError: too many arguments for format string</p>
<p>That doesn't seem right. Is it an error or isn't it?</p>
<p>For too few arguments it is always an error:</p>
<p>"%s" % [] #=> ArgumentError: too few arguments</p>
<p>Personally, I think it should use '' for missing arguments. That would make it more flexible in practice.</p>
<p>I consider the first $DEBUG issue a bug, and the later a feature. But I'll just call it a feature altogether to make things easier.</p> Ruby master - Feature #5478 (Open): Add syntax to import Set into corehttps://bugs.ruby-lang.org/issues/54782011-10-25T03:46:12Zrkh (Konstantin Haase)me@rkh.im
<p>Set is a central data structure. However, a lot of Ruby developers use arrays for situations where it would be more reasonable to use a set. One reason for that is that it is way easier to use Array than Set at the moment. Another one is that developers are simply not aware that it exists.</p>
<p>I propose to move Set from <code>stdlib</code> to core and possibly add a literal syntax or a method on array for creating a Set.</p>
<p>First class syntax suggestions:</p>
<pre><code><1, 2, 3> # might be tricky to parse
#[1, 2, 3] # would collide with comments
$[1, 2, 3]
${1, 2, 3}
</code></pre>
<p>Method suggestions:</p>
<pre><code>~[1, 2, 3]
+[1, 2, 3]
</code></pre>
<p>Whitespace separated String Sets could look like this:</p>
<pre><code>%w<foo bar blah> # creates an array at the moment
#w[foo bar blah] # would collide with comments
$w[foo bar blah] # would collide with sending :[] to $w
$w{foo bar blah}
~%w[foo bar blah] # not really shorter than using an array with strings
+%w[foo bar balh] # not really shorter than using an array with strings
</code></pre>
<p>Maybe it's ok to not have a whitespace separated syntax. I'm just brainstorming here.</p>
<p>An issue with the method approach is that it would create an Array first to which the message would be sent.</p>
<p>I favor the <code><1, 2, 3></code> syntax, possibly without the ability to create a whitespace separated version.</p>
<p>I'd be willing to work on a patch not only for MRI but also for JRuby and Rubinius if you would consider this to be useful although I would need help with the parser.</p> Ruby master - Feature #5461 (Assigned): Add pipelining to Net::HTTPhttps://bugs.ruby-lang.org/issues/54612011-10-19T07:37:41Zdrbrain (Eric Hodel)drbrain@segment7.net
<p>=begin<br>
The attached patch adds HTTP/1.1 pipelining support to Net::HTTP.</p>
<p>Pipelining is only performed on HTTP/1.1 servers. Net::HTTP will check if the server supports pipelining by using the first request in the list. The user can override this via setting (({http.pipelining = true})).</p>
<p>If a server does not support pipelining or there is an error during pipelining an error will be raised that contains the requests that not have been delivered yet and the responses that have been received.</p>
<p>The patch includes documentation explaining the fine details.</p>
<p>Example:</p>
<p>requests = []<br>
requests << Net::HTTP::Get.new('/images/bug.png')<br>
requests << Net::HTTP::Get.new('/images/date.png')<br>
requests << Net::HTTP::Get.new('/images/find.png')</p>
<p>http = Net::HTTP.new 'localhost'<br>
http.start do<br>
http.pipeline requests do |req, res|<br>
open File.basename(req.path), 'wb' do |io|<br>
io.write res.body<br>
end<br>
end<br>
end</p>
<p>Implementation notes:</p>
<ul>
<li>The current Net::HTTP tests make it very difficult to test bad behavior by servers. In test/net/http/utils.rb I introduced a method to replace Net::BufferedIO with a subclass that can behave incorrectly.</li>
<li>Net::HTTP#pipeline does not fall back to sending requests one-by-one for HTTP/1.1 servers. I think this is acceptable as the user can use existing Net::HTTP code to send requests one-by-one.</li>
</ul>
<p>=end</p> Ruby master - Feature #5456 (Assigned): kernel#syscall() should be removed.https://bugs.ruby-lang.org/issues/54562011-10-18T04:06:16Zkosaki (Motohiro KOSAKI)kosaki.motohiro@gmail.com
<p>It doesn't works correctly a long time. It's not portable and JRuby have no chance to implement it.<br>
Moreover, Fiddle provides better interface.</p> Ruby master - Feature #5445 (Assigned): Need RUBYOPT -r before ARGV -rhttps://bugs.ruby-lang.org/issues/54452011-10-14T00:47:09Ztrans (Thomas Sawyer)
<p>Libraries given by -r options in RUBYOPT should be loaded before ones in direct command line arguments.</p>
<p>I use a custom load system for development that I have been using for years and it works very well for me. But Ruby has some edge cases that prevents it from being feature complete. One of these is the order in which RUBYOPT is applied vs. -r command line option.</p>
<p>My custom loader is too large to include here, so I will simply demonstrate the problem with simple sample code:</p>
<p>$ cat req.rb<br>
p "Custom Require"</p>
<p>module Kernel<br>
alias :require0 :require</p>
<pre><code>def require(*a)
puts "Kernel#require"
p a
require0(*a)
end
class << self
alias :require0 :require
def require(*a)
puts "Kernel.require"
p a
require0(*a)
end
end
</code></pre>
<p>end</p>
<p>If we load this via RUBYOPT, the result is:</p>
<p>$ RUBYOPT=-r./req.rb ruby -rstringio -e0<br>
Custom Require</p>
<p>But if we load via -r the result is:</p>
<p>$ ruby -r./req.rb -rstringio -e0<br>
Custom Require<br>
Kernel#require<br>
["stringio"]</p>
<p>I would ask that the output of both invocations to be identical.</p>
<p>(Note, the -T option should still allow RUBYOPT to be omitted regardless.)</p> Ruby master - Feature #5434 (Assigned): Allow per-class whitelisting of methods safe to expose th...https://bugs.ruby-lang.org/issues/54342011-10-11T13:11:08Zshyouhei (Shyouhei Urabe)shyouhei@ruby-lang.org
<p>We have following pull-request.</p>
<p><a href="https://github.com/ruby/ruby/pull/50" class="external">https://github.com/ruby/ruby/pull/50</a></p>
<p>How do you feel? I can merge this if you are OK.</p> Ruby master - Feature #5389 (Assigned): New method Enumerator#iteratehttps://bugs.ruby-lang.org/issues/53892011-10-03T20:25:16Zyimutang (Joey Zhou)
<p>If we want to iterate over the elements of a enumerable object with <em>multiple</em> blocks, we can use the Enumerator class.</p>
<p>A method 'iterate' is required, we can write it in Ruby:</p>
<pre><code>class Enumerator
def iterate
yield_value = self.next
return_value = yield yield_value
self.feed return_value
self
end
end
</code></pre>
<p>Well, here is an example:</p>
<pre><code>array = (1..10).to_a
enum = array.map!
loop do
enum.iterate {|n| n + 10 }
enum.iterate {|n| n * 2 }
enum.iterate {|n| -n }
end
p array # => [11, 4, -3, 14, 10, -6, 17, 16, -9, 20]
</code></pre>
<p>We want to map an array: the 1st element use blk1, the 2nd use blk2, the 3rd use blk3...</p>
<p>I think this Enumerator#iterate method is sometimes useful, so would you please introduce it into the language core?</p> Ruby master - Feature #5310 (Assigned): Integral objectshttps://bugs.ruby-lang.org/issues/53102011-09-13T10:15:48Zmrkn (Kenta Murata)muraken@gmail.com
<p>I believe it is ambiguous what object can behave as an integral number.<br>
I don't think the current use of Object#to_int isn't appropriate for this purpose.</p>
<p>The most understandable example is Float#to_int.<br>
It should raise error for all float values because they always have uncertainty,<br>
but it doesn't and returns an integral part of it.</p>
<p>I propose to change the use of Object#to_int for the next release of Ruby.<br>
I recommend the following specification changes:</p>
<p>(1) Remove to_int method from Float and BigDecimal.<br>
(2) Rational#to_int returns an Integer only if its denominator is 1. Otherwise, it raises an appropriate error.<br>
(3) Complex#to_int returns the result of to_int of its real part only if its imaginary part is exactly zero (0.0 isn't exactly zero).</p>
<p>If anyone have another idea, please give me your comment.</p> Ruby master - Feature #5133 (Assigned): Array#unzip as an alias of Array#transposehttps://bugs.ruby-lang.org/issues/51332011-08-01T18:30:03Zmrkn (Kenta Murata)muraken@gmail.com
<p>Array#zip の逆は Array#transpose なんですけど、<br>
この対応関係が非常に分かり難いなと思いました。</p>
<p>Haskell には zip の逆をやる関数として unzip が用意されています。<br>
unzip という名前は、「zip の逆をやりたい」と思ったときに<br>
(transpose よりは) 思い付きやすい名前だと思います。</p>
<p>ということで Array#unzip を Array#transpose のエイリアスとして<br>
導入してはどうでしょう?</p>
<p>以下パッチです:</p>
<p>diff --git a/array.c b/array.c<br>
index 8caad66..dc411b7 100644<br>
--- a/array.c<br>
+++ b/array.c<br>
@@ -4720,6 +4720,7 @@ Init_Array(void)<br>
rb_define_method(rb_cArray, "reject!", rb_ary_reject_bang, 0);<br>
rb_define_method(rb_cArray, "zip", rb_ary_zip, -1);<br>
rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0);</p>
<ul>
<li>rb_define_alias(rb_cArray, "unzip", "transpose");<br>
rb_define_method(rb_cArray, "replace", rb_ary_replace, 1);<br>
rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);<br>
rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);</li>
</ul> Ruby master - Feature #5129 (Assigned): Create a core class "FileArray" and make "ARGF" its instancehttps://bugs.ruby-lang.org/issues/51292011-08-01T13:57:46Zyimutang (Joey Zhou)
<p>I suggest to create a class "<code>FileArray</code>" whose instance behaves just like <code>ARGF</code> do.<br>
And I think <code>ARGF</code> should be an instance of <code>FileArray</code>. Now when I "<code>p ARGF.class</code>", I get "<code>ARGF.class</code>", so <code>ARGF</code> is an instance of <code>ARGF.class</code>, how meaningless it is.</p>
<p>FileArray methods:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="c1"># create an instance</span>
<span class="n">fa</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'a.txt'</span><span class="p">,</span><span class="s1">'b.txt'</span><span class="p">,</span><span class="s1">'c.txt'</span><span class="p">)</span>
<span class="c1"># take many methods from IO</span>
<span class="c1"># most methods from ARGF should be instance methods of ARGF </span>
<span class="n">fa</span><span class="p">.</span><span class="nf">each</span> <span class="p">{</span><span class="o">|</span><span class="n">line</span><span class="o">|</span> <span class="nb">puts</span> <span class="n">line</span> <span class="p">}</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">realines</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># current file</span>
<span class="c1"># but "argv" not</span>
<span class="nb">p</span> <span class="n">fa</span><span class="p">.</span><span class="nf">file_list</span> <span class="c1"># in ARGF, its ARGF.argv, but #argv is not a proper name for FileArray</span>
<span class="c1"># ARGV array can be modified, adding new file into it, all replace to a new file list.</span>
<span class="c1"># FileArray should add some methods to modify the inner file list.</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">insert</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="s2">"d.txt"</span><span class="p">)</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="s1">'a.txt'</span><span class="p">)</span>
</code></pre>
<p>With <code>FileArray</code>, You can create multiple <code>ARGF</code>-like file arrays simultaneously.</p>
<p>For example, I want to mix two <em>groups</em> of files, not two files:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">a_files</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="o">*</span><span class="no">Dir</span><span class="p">.</span><span class="nf">glob</span><span class="p">(</span><span class="s1">'a*.txt'</span><span class="p">))</span>
<span class="n">b_files</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="o">*</span><span class="no">Dir</span><span class="p">.</span><span class="nf">glob</span><span class="p">(</span><span class="s1">'b*.txt'</span><span class="p">))</span>
<span class="n">enum_a</span> <span class="o">=</span> <span class="n">a_files</span><span class="p">.</span><span class="nf">each</span>
<span class="n">enum_b</span> <span class="o">=</span> <span class="n">b_files</span><span class="p">.</span><span class="nf">each</span>
<span class="kp">loop</span> <span class="k">do</span>
<span class="nb">puts</span> <span class="n">enum_a</span><span class="p">.</span><span class="nf">next</span>
<span class="nb">puts</span> <span class="n">enum_b</span><span class="p">.</span><span class="nf">next</span>
<span class="k">end</span>
</code></pre> Ruby master - Feature #5064 (Assigned): HTTP user-agent classhttps://bugs.ruby-lang.org/issues/50642011-07-21T13:10:00Zdrbrain (Eric Hodel)drbrain@segment7.net
<p>Currently there are some problems with Net::HTTP:</p>
<ul>
<li>Too many ways to use (user confusion)</li>
<li>No automatic support for HTTPS (must conditionally set use_ssl)</li>
<li>No automatic support for HTTPS peer verification (must be manually set)</li>
<li>Single-connection oriented</li>
<li>No support for redirect-following</li>
<li>No support for HTTP/1.1 persistent connection retry (RFC 2616 8.1.4)</li>
<li>No automatic support for HTTP proxies</li>
<li>No automatic support for authentication (must be set per-request)</li>
</ul>
<p>Additionally the style of the API of Net::HTTP makes it difficult to take advantage of persistent connections. The user has to store the created connection and manually handle restarting the connection if it has timed out or is closed by the server.</p>
<p>RFC 2616 8.1.1 has a large section explaining the benefits of persistent connections, but while Net::HTTP implements persistent connections they could be easier for users to implement with next work.</p>
<p>I've implemented support for many of these additional features of Net::HTTP in various projects and I'd like Ruby to have the features required to make a useful HTTP user-agent built-in.</p>
<p>The agent should have the following responsibilities:</p>
<ul>
<li>Make or reuse connections based on [host, port, SSL enabled]</li>
<li>Automatically enable SSL for https URIs</li>
<li>Automatically enable SSL peer verification for SSL connections</li>
<li>Limit number of persistent connections per host</li>
<li>Follow redirects</li>
<li>Retry when a persistent connection fails</li>
<li>Automatically configure proxies</li>
<li>Automatically use authentication</li>
<li>Callbacks for various options connect</li>
</ul>
<p>The agent may add the following responsibilities:</p>
<ul>
<li>Default headers for all requests</li>
<li>HTTP cookies</li>
<li>Tracking history</li>
<li>Logging</li>
</ul>
<p>I don't think any of these features are critical as they are implementable by users via callbacks.</p>
<p>The agent would have the following configurable items:</p>
<ul>
<li>Number of connections per host</li>
<li>Depth of redirects followed</li>
<li>Persistent connection retries (none, HTTP/1.1 (default), always)</li>
<li>Proxy host, port, user, password</li>
</ul>
<p>I think the class should be called Net::HTTP::Agent.</p>
<p>Basic use would look something like this:</p>
<p>uris = [<br>
URI('http://example/1'),<br>
URI('http://example/2'),<br>
URI('https://secure.example'),<br>
]</p>
<p>agent = Net::HTTP::Agent.new</p>
<p>uris.map do |uri|<br>
agent.get uri # Returns Net::HTTPResponse<br>
end</p>
<p>For special requests a Net::HTTPRequest could be constructed:</p>
<p>req = Net::HTTP::Get.new uri.request_uri</p>
<a name="do-something-special-with-req"></a>
<h1 >do something special with req<a href="#do-something-special-with-req" class="wiki-anchor">¶</a></h1>
<p>agent.request req</p>
<p>The agent should support GET, POST, etc. directly through API methods. I think the API should look something like this:</p>
<p>def get uri_or_string, query = nil, headers = nil</p>
<a name="Same-for-other-requests-with-no-body"></a>
<h1 >Same for other requests with no body<a href="#Same-for-other-requests-with-no-body" class="wiki-anchor">¶</a></h1>
<h1></h1>
<a name="query-may-be-a-Hash-or-String"></a>
<h1 >query may be a Hash or String<a href="#query-may-be-a-Hash-or-String" class="wiki-anchor">¶</a></h1>
<a name="How-query-param-vs-query-string-in-URI-is-used-is-undecided"></a>
<h1 >How query param vs query string in URI is used is undecided<a href="#How-query-param-vs-query-string-in-URI-is-used-is-undecided" class="wiki-anchor">¶</a></h1>
<p>def post uri_or_string, data, headers = nil</p>
<a name="same-for-other-requests-with-a-body"></a>
<h1 >same for other requests with a body<a href="#same-for-other-requests-with-a-body" class="wiki-anchor">¶</a></h1>
<h1></h1>
<a name="data-may-be-a-String-IO-or-Hash"></a>
<h1 >data may be a String, IO or Hash<a href="#data-may-be-a-String-IO-or-Hash" class="wiki-anchor">¶</a></h1>
<a name="How-data-format-is-chosen-is-undecided"></a>
<h1 >How data format is chosen is undecided<a href="#How-data-format-is-chosen-is-undecided" class="wiki-anchor">¶</a></h1>
<p>SSL options, proxy options, timeouts and similar options should exist on Net::HTTP::Agent and be set on new connections as they are made.</p>
<p>I've implemented most of these features in mechanize as Mechanize::HTTP::Agent. The Agent class in mechanize is bigger than is necessary and would need to be cut-down for inclusion in Ruby as Net::HTTP::Agent</p>
<p><a href="https://github.com/tenderlove/mechanize/blob/master/lib/mechanize/http/agent.rb" class="external">https://github.com/tenderlove/mechanize/blob/master/lib/mechanize/http/agent.rb</a></p>
<p>Mechanize depends on net-http-persistent to provide HTTP/1.1 retry support and connection management:</p>
<p><a href="https://github.com/drbrain/net-http-persistent/blob/master/lib/net/http/persistent.rb" class="external">https://github.com/drbrain/net-http-persistent/blob/master/lib/net/http/persistent.rb</a></p>
<p>Portions of net-http-persistent should be patches of Net::HTTP, for example #idempotent? #can_retry?, #reset and portions of #request. Other parts (connection management) should be moved to Net::HTTP::Agent.</p>
<p>net-http-persistent provides a separate connection list per thread. I would like Net::HTTP::Agent to be multi-thread friendly but implementing this in another way would be fine.</p>
<p>As an addendum, open-uri and mechanize should be written to take advantage of Net::HTTP::Agent on order to guide useful implementation.</p> Ruby master - Feature #5007 (Assigned): Proc#call_under: Unifying instance_eval and instance_exechttps://bugs.ruby-lang.org/issues/50072011-07-09T23:26:49Zjudofyr (Magnus Holm)judofyr@gmail.com
<p>I'm proposing a method called <code>Proc#call_under</code> (the name could be<br>
discussed) which both unifies <code>instance_eval</code> and <code>instance_exec</code>, and makes<br>
it possible to call a <code>Proc</code> with a block and a scope:</p>
<p><code>Proc#call_under(self, *args, &blk)</code>:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">proc</span> <span class="p">{</span> <span class="nb">self</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => 1</span>
<span class="nb">proc</span> <span class="p">{</span> <span class="o">|</span><span class="n">a</span><span class="o">|</span> <span class="nb">self</span> <span class="o">+</span> <span class="n">a</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c1"># => 3</span>
<span class="nb">proc</span> <span class="p">{</span> <span class="o">|&</span><span class="n">b</span><span class="o">|</span> <span class="nb">self</span> <span class="o">+</span> <span class="n">b</span><span class="p">.</span><span class="nf">call</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="p">{</span> <span class="mi">2</span> <span class="p">}</span> <span class="c1"># => 4</span>
</code></pre> Ruby master - Feature #4924 (Assigned): mkmf have_header fails with C++ headershttps://bugs.ruby-lang.org/issues/49242011-06-24T12:09:56Zadgar (Michael Edgar)michael.j.edgar@dartmouth.edu
<p>=begin<br>
When a user calls (({have_header('some_cpp_header.h')})), and then header includes a line such as(({ #include })), mkmf will fail.</p>
<p>An example run follows:</p>
<ul>
<li>
<p>extconf.rb</p>
<p>require 'mkmf'<br>
have_library('stdc++')<br>
have_header('BasicBlock.h')<br>
create_makefile('laser/BasicBlock')</p>
</li>
<li>
<p>mkmf.log<br>
have_header: checking for BasicBlock.h... -------------------- no</p>
<p>"gcc -E -I/Users/michaeledgar/.rvm/rubies/ruby-1.9.2-head/include/ruby-1.9.1/x86_64-darwin10.7.0 -I/Users/michaeledgar/.rvm/rubies/ruby-1.9.2-head/include/ruby-1.9.1/ruby/backward -I/Users/michaeledgar/.rvm/rubies/ruby-1.9.2-head/include/ruby-1.9.1 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -O3 -ggdb -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-missing-field-initializers -Wshorten-64-to-32 -Wno-long-long -fno-common -pipe conftest.c -o conftest.i"<br>
In file included from conftest.c:3:<br>
./BasicBlock.h:4:18: error: vector: No such file or directory<br>
./BasicBlock.h:5:21: error: exception: No such file or directory<br>
./BasicBlock.h:6:21: error: stdexcept: No such file or directory<br>
checked program was:<br>
/* begin <em>/<br>
1: #include "ruby.h"<br>
2:<br>
3: #include <BasicBlock.h><br>
/</em> end */</p>
</li>
</ul>
<p>The issue here is that the temporary file created to perform the header test is ((%conftest.c%)), not ((%conftest.cc%)) or ((%conftest.cpp%)). Changing the<br>
name of the file and re-running gcc gives success.</p>
<p>In ((%mkmf.rb%)), have_header executes cpp_command, which creates the shell command to run. However, cpp_command uses the constant (({CONFTEST_C = "conftest.c"})). It should use a new constant, (({CONFTEST_CPP = "conftest.cc"})).</p>
<p>I've attached a patch that does this as expected. Tests pass; I'm unsure precisely how to construct<br>
a test case that would be appropriate for the Ruby trunk. There are very few guiding examples in the<br>
existing test suite.</p> Ruby master - Feature #4831 (Assigned): Integer#prime_factorshttps://bugs.ruby-lang.org/issues/48312011-06-06T00:33:11Zmame (Yusuke Endoh)mame@ruby-lang.org
<p>Hello,</p>
<p>lib/prime provides Integer#prime_division, but I always forget the name.<br>
I think that #prime_factors is more suitable. I'd like to hear opinions<br>
of English natives. What do you think?</p>
<p>--<br>
Yusuke Endoh <a href="mailto:mame@tsg.ne.jp" class="email">mame@tsg.ne.jp</a></p> Ruby master - Feature #4824 (Assigned): Provide method Kernel#executed?https://bugs.ruby-lang.org/issues/48242011-06-04T19:59:21Zlazaridis.com (Lazaridis Ilias)ilias@lazaridis.com
<p>The current construct to execute main code looks not very elegant:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">if</span> <span class="kp">__FILE__</span> <span class="o">==</span> <span class="vg">$0</span>
<span class="n">my_main</span><span class="p">()</span> <span class="c1"># call any method or execute any code</span>
<span class="k">end</span>
</code></pre>
<p>With a <code>Kernel#executed?</code> method, this would become more elegant:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">if</span> <span class="n">executed?</span>
<span class="c1">#do this</span>
<span class="c1">#do that</span>
<span class="n">my_main</span><span class="p">()</span>
<span class="k">end</span>
</code></pre>
<p>or</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">main</span><span class="p">()</span> <span class="k">if</span> <span class="n">executed?</span>
</code></pre>
<p>This addition would not break any existent behaviour.</p> Ruby master - Feature #4818 (Assigned): Add method marshalable?https://bugs.ruby-lang.org/issues/48182011-06-03T11:07:15Zyimutang (Joey Zhou)
<p>Some objects can not be marshaled. Maybe there should be a method to tell it.</p>
<p>hash = Hash.new {|h,k| k * 2}</p>
<p>this hash can't be marshaled because it has a default proc. If existing such method:</p>
<p>Marshal.marshalable?(hash) #=> method "Marshal.marshalable?"<br>
hash.marshalable? #=> method "Kernel#marshalable?"</p>
<p>If you think the method name hard to spell, maybe get a synonym "dumpable?"</p> Ruby master - Feature #4592 (Assigned): Tempfileを直接保存したいhttps://bugs.ruby-lang.org/issues/45922011-04-21T16:43:31Zxibbar (Takeyuki FUJIOKA)xibbar@gmail.com
<p>=begin<br>
Tempfileは一時ファイルなので、プロセスが消えたり、#closeすると、<br>
ファイルが消えてしまいます。<br>
Tempfileのデータを保存するために<br>
一旦読みだして、書き込み用に別ファイルを開いて、<br>
そこに書きこまなければいけません。<br>
これが小さいファイルだったらいいのですが、<br>
大きいファイルになると、<br>
Tempfile#save みたいなメソッドを用意して、<br>
closeと同時に保存ができると、<br>
読みだして書きこむという無駄をなくすことができます。<br>
10MB程度だったらいいのですが、500MとかのTempfileだと<br>
かなり有効なメソッドだと思います。</p>
<p>#save とか #save! とか、何がいいかは議論の余地があると思います。<br>
=end</p> Ruby master - Feature #4539 (Assigned): Array#zip_withhttps://bugs.ruby-lang.org/issues/45392011-03-30T06:21:32Zcitizen428 (Michael Kohl)citizen428@gmail.com
<p>Inspired by Haskell's <code>zipWith</code> function, I hacked on together for Ruby:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">].</span><span class="nf">zip_with</span><span class="p">([</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="p">:</span><span class="o">+</span><span class="p">)</span> <span class="c1">#=> [7, 7, 7]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">].</span><span class="nf">zip_with</span><span class="p">([</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span> <span class="p">{</span> <span class="o">|</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="o">|</span> <span class="mi">3</span><span class="o">*</span><span class="n">a</span><span class="o">+</span><span class="mi">2</span><span class="o">*</span><span class="n">b</span> <span class="p">}</span> <span class="c1">#=> [15, 16, 17]</span>
</code></pre>
<p>So far I only have a Ruby version of it:</p>
<p><a href="https://gist.github.com/731702b90757e21cadcb" class="external">https://gist.github.com/731702b90757e21cadcb</a></p>
<p>My questions:</p>
<ol>
<li>
<p>Would this method be considered a worthwhile addition to <code>Array</code>?</p>
</li>
<li>
<p>I've never hacked on the C side of Ruby (read some parts of the source though) and my C is quite rusty. I'd like to change that, would somebody be willing to help me turn this into a proper patch?</p>
</li>
</ol> Ruby master - Feature #4521 (Assigned): NoMethodError#message may take very long to executehttps://bugs.ruby-lang.org/issues/45212011-03-25T04:59:14Zadiel.mittmann (Adiel Mittmann)adiel@inf.ufsc.br
<p>=begin<br>
When a non-existing method is called on an object, NoMethodError is risen. If you call #message, however, your code may use up all CPU for a very long time (in my case, up to a few minutes).</p>
<p>I narrowed the problem down to this code in error.c (SVN snapshot) in the function name_err_mesg_to_str():</p>
<p>d = rb_protect(rb_inspect, obj, 0);<br>
if (NIL_P(d) || RSTRING_LEN(d) > 65) {<br>
d = rb_any_to_s(obj);<br>
}</p>
<p>The problem is that, for a complex object, #inspect may take very long to execute, only to have its results thrown away because they will be larger than 65 characters.</p>
<p>Of course I can write a #to_s for all my objects, but the point is that I didn't call #to_s or #inspect, I called #message on an exception object, which then takes a few minutes just to return a short string.</p>
<p>Needless to say, this might be easy to spot in a simple example, but once you're writing a web application that suddenly freezes for one minute with no apparent reason, you're all but clueless as to what's going on. (The first time this happened, I didn't even know that something would eventually show up on the screen -- I thought it was an infinite loop).</p>
<p>Here's an example code that shows this behavior:</p>
<p>require 'nokogiri'<br>
class A<br>
def x<br>
@xml = Nokogiri::XML(File.new('baz.xml', 'rb').read())<br>
foo()<br>
end<br>
end<br>
A.new().x()<br>
a.x</p>
<p>Here, the time it takes for Ruby to print out the message that #foo doesn't exist is proportional to the size of baz.xml.</p>
<p>As a comparison, Python doesn't seem to do this. Take the following code:</p>
<p>class Test:<br>
def <strong>str</strong>(self):<br>
return "hello"<br>
a = Test()<br>
print a<br>
print a.x()</p>
<p>If you execute it, this is the result:</p>
<p>hello<br>
Traceback (most recent call last):<br>
File "test.py", line 6, in <br>
print a.x()<br>
AttributeError: Test instance has no attribute 'x'</p>
<p>It uses the method <strong>str</strong> to convert the object to a string when necessary, but doesn't use it when printing out the message stating that the attribute doesn't exist.</p>
<p>One obvious way to fix this would be to always print out the simpler representation given by rb_any_to_s.<br>
=end</p> Ruby master - Feature #4514 (Assigned): #deep_clone and #deep_dup for Objectshttps://bugs.ruby-lang.org/issues/45142011-03-21T19:23:02Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
There's often a need to do a deep clone of an object, especially of Hash/Array trees. The typical work around to the lack of this functionality is to Marshall and then Unmarshall (e.g. Marshal::load(Marshal::dump(self)) ), which incurs more overhead than it probably should, and is not very semantic. My suggestion is to either provide #deep_clone and #deep_dup methods on the Object class, or to at least provide equivalent functionality for Hashes and Arrays, such as possibly a #deep_merge method for Hash. The exact implantation is not a large concern of mine; I'll let the experts determine the best method of achieving the desired outcome.<br>
=end</p> Ruby master - Feature #4464 (Assigned): [PATCH] add Fcntl::Flock object for easier use of POSIX f...https://bugs.ruby-lang.org/issues/44642011-03-04T04:42:38Znormalperson (Eric Wong)normalperson@yhbt.net
<p>=begin<br>
This is a subclass of String so it is compatible with<br>
IO#fcntl without needing to modify io.c for systems<br>
that don't have POSIX file locks.<br>
=end</p> Ruby master - Feature #3953 (Assigned): TCPSocket / UDPSocket do not accept IPAddr objects.https://bugs.ruby-lang.org/issues/39532010-10-16T20:41:59Zpostmodern (Hal Brodigan)postmodern.mod3@gmail.com
<p>=begin<br>
I noticed that TCPSocket/UDPSocket only accept String IPs/Hostnames, but not IPAddr objects. This is counter-intuitive since IP Addresses, along with Hostnames, are used to connect/bind to sockets.</p>
<pre><code> require 'socket'
require 'resolv'
ip = IPAddr.new(Resolv.getaddress('www.example.com'))
sock = TCPSocket.new(ip,80)
TypeError: can't convert IPAddr into String
from (irb):5:in `initialize'
from (irb):5:in `new'
from (irb):5
</code></pre>
<p>=end</p> Ruby master - Feature #3731 (Assigned): Easier Embedding API for Rubyhttps://bugs.ruby-lang.org/issues/37312010-08-22T07:16:50ZBeoran (Beoran Aegul)beoran@rubyforge.org
<p>=begin<br>
With Ruby 1.9, it has become more difficult to embed Ruby in a C application correctly.<br>
It would be nice if there was a clearly documented and simple C API to embed ruby in C programs.<br>
I know Ruby was not designed from the start to be embedded, but Ruby was used before in several<br>
products as an embedded scripting langauge. It should therefore be possible to do so in a<br>
more straightforward way.</p>
<p>Kind Regards,</p>
<p>B.<br>
=end</p> Ruby master - Feature #3608 (Assigned): Enhancing Pathname#each_child to be lazyhttps://bugs.ruby-lang.org/issues/36082010-07-24T10:27:14Ztaw (Tomasz Wegrzanowski)Tomasz.Wegrzanowski@gmail.com
<p>=begin<br>
Right now it lists entire directory, then yields<br>
every element, that is x.each_child(&b) means x.children.each(&b).</p>
<p>This is too slow for directories mounted over networked file systems etc.,<br>
and there is currently no way to get lazy behaviour, other than leaving<br>
convenient #each_child/#children API and moving to lower level.</p>
<p>With this patch:</p>
<ul>
<li>#children is eager like before, no change here</li>
<li>#each_child becomes lazy</li>
<li>#each_child without block returns lazy enumerator,<br>
so it can be used like this dir.each_child.find(&:symlink?)<br>
without losing laziness.</li>
</ul>
<p>Patch is against trunk. pathname.rb was in lib/ not ext/pathname/lib/<br>
before, but it works either way.</p>
<p>The part to return enumerator when called without a block wouldn't<br>
work in 1.8. If backport is desired, that line would need to be thrown<br>
away, and #children would need to build result array instead<br>
of calling each_child(with_directory).to_a - this would be straightforward.<br>
=end</p> Ruby master - Feature #2631 (Assigned): Allow IO#reopen to take a blockhttps://bugs.ruby-lang.org/issues/26312010-01-23T00:55:49Zdjberg96 (Daniel Berger)
<p>=begin<br>
Please allow IO#reopen to accept a block. This would allow users to temporarily redirect output without having to manually reset the file descriptor. For example:</p>
<p>require 'mkmf'</p>
<a name="stdout-redirected-within-block-only"></a>
<h1 >stdout redirected within block only<a href="#stdout-redirected-within-block-only" class="wiki-anchor">¶</a></h1>
<p>$stdout.reopen('/dev/null') do<br>
if have_header('foo.h')<br>
# Do stuff<br>
end<br>
end</p>
<a name="stdout-now-back-to-its-former-setting"></a>
<h1 >stdout now back to its former setting<a href="#stdout-now-back-to-its-former-setting" class="wiki-anchor">¶</a></h1>
<p>I believe this is both convenient and intuitive when one considers the IO.open also takes a block.</p>
<p>Regards,</p>
<p>Dan<br>
=end</p> Ruby master - Feature #2324 (Assigned): Dir instance methods for relative pathhttps://bugs.ruby-lang.org/issues/23242009-11-02T17:48:30Znobu (Nobuyoshi Nakada)nobu@ruby-lang.org
<p>なかだです。</p>
<p><a href="http://www.ipa.go.jp/security/fy20/reports/tech1-tg/2_05.html" class="external">http://www.ipa.go.jp/security/fy20/reports/tech1-tg/2_05.html</a> を<br>
みて思い出したんですが、相対パスを使う<code>Dir</code>のインスタンスメソッド<br>
はどうでしょうか。実装はmvmブランチにあります。</p>
<pre><code>$ ./ruby -v -e 'p Dir.open("ext"){|d|d.open("extmk.rb"){|f|f.gets}}'
ruby 1.9.1 (2008-12-25 mvm 20976) [i686-linux]
"#! /usr/local/bin/ruby\n"
$ mkdir tmp
$ touch tmp/x tmp/y
$ ./ruby -e 'p Dir.open("tmp"){|d|d.unlink("x")}'
0
$ ls tmp/
y
</code></pre>
<p>--<br>
--- 僕の前にBugはない。<br>
--- 僕の後ろにBugはできる。<br>
中田 伸悦</p> Ruby master - Feature #2294 (Assigned): [PATCH] ruby_bind_stack() to embed Ruby in coroutinehttps://bugs.ruby-lang.org/issues/22942009-10-28T02:02:58Zsunaku (Suraj Kurapati)sunaku@gmail.com
<p>=begin<br>
Hi,</p>
<p>I am attaching a "ruby_bind_stack.patch" patch file<br>
that adds a ruby_bind_stack() function to the Ruby C API.</p>
<p>This function allows me to inform the GC about the stack<br>
boundaries of the coroutine inside which Ruby is embedded:</p>
<p>void ruby_bind_stack(void *lower, void *upper);</p>
<p>I am also attaching tarballs containing code examples that<br>
embed Ruby inside two different coroutine environments:<br>
UNIX System V contexts<a href="http://www.gnu.org/s/libc/manual/html_node/System-V-contexts.html" class="external">1</a> and libpcl<a href="http://www.xmailserver.org/libpcl.html" class="external">2</a> coroutines.</p>
<p>Each tarball has an "output.log" file which contains the<br>
result of running <code>script -c ./run.sh output.log</code> on my<br>
machine:</p>
<p>Linux yantram 2.6.31-ARCH #1 SMP PREEMPT Tue Oct 13 13:36:23 CEST 2009 i686 Intel(R) Pentium(R) D CPU 3.00GHz GenuineIntel GNU/Linux</p>
<p>The last section in "output.log" corresponds to Ruby @ SVN<br>
trunk that is patched with the "ruby_bind_stack.patch"<br>
patch file that is attached to this issue.</p>
<p>Thanks for your consideration.</p>
<p>See also:</p>
<ul>
<li><a href="http://redmine.ruby-lang.org/issues/show/2258" class="external">http://redmine.ruby-lang.org/issues/show/2258</a></li>
<li>
<a href="http://redmine.ruby-lang.org/issues/show/2126" class="external">http://redmine.ruby-lang.org/issues/show/2126</a><br>
=end</li>
</ul> Ruby master - Feature #1644 (Assigned): recv on inherited socket wrapped in TCPSocket does not re...https://bugs.ruby-lang.org/issues/16442009-06-17T14:37:54Zkntuaf (Kedar H)knutaf@gmail.com
<p>=begin<br>
On Windows, if you try to wrap an existing winsock socket that was inherited from a parent process into a TCPSocket, any calls to recv on this socket in the child process will not retrieve any data.</p>
<p>This is because the inherited socket is not a member of the internal "socklist" structure in win32.c. rb_w32_select filters out all sockets that are not in this internal list, prior to calling ws2_32!select.</p>
<p>One good solution is for TCPSocket.for_fd to make sure to insert its argument into the socklist structure so that subsequent Winsock functions wrapped by Ruby will work as though the socket were created by this Ruby process. Another possible solution is to expose another method, something like TCPSocket.from_new_fd.<br>
=end</p>