Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112013-10-22T21:16:59ZRuby Issue Tracking System
Redmine Ruby master - Feature #9043 (Open): Add String#f method as shortcut for #freezehttps://bugs.ruby-lang.org/issues/90432013-10-22T21:16:59Zheadius (Charles Nutter)headius@headius.com
<p>We have String#b to create a binary-encoded String, and we have the "f" suffix (going away, hopefully) and the "literal".freeze optimization (<a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: Use String#freeze and compiler tricks to replace "str"f suffix (Closed)" href="https://bugs.ruby-lang.org/issues/8992">#8992</a>). I think it would be reasonable to add String#f as a shorter method for producing a frozen string.</p>
<p>If String#f is added the "literal".freeze optimization could be dropped in favor of "literal".f. This would provide something very close to the original "literal"f syntax but in a backward-compatibility-friendly way (class String; alias f freeze; end).</p> Ruby master - Feature #8994 (Open): add methods for Float to get if an NaN is quiet or not, also ...https://bugs.ruby-lang.org/issues/89942013-10-08T16:45:30ZHanmac (Hans Mackowiak)hanmac@gmx.de
<p>Currently its not easy possible to know of an NaN in ruby is silent or not</p>
<p>like Float::NAN.quiet?</p>
<p>there should also methods to make an new NaN like Float::quiet_nan, maybe with the possibility to set user data</p>
<p>also there is</p>
<p>[Float::NAN].pack("g") #=> "\x7F\xC0\x00\x00"<br>
[0.0/0.0].pack("g") #=> "\xFF\xC0\x00\x00"</p>
<p>and</p>
<p>[-(0.0/0.0)].pack("g") #=> "\x7F\xC0\x00\x00"</p>
<p>so it seems that - can turn an quiet NaN into an loud one? (i am not 100% clear about that)<br>
specially when using two different NaN in one operation like</p>
<p>[(0.0/0.0) + Float::NAN].pack("g") #=> "\xFF\xC0\x00\x00"<br>
[Float::NAN + (0.0/0.0)].pack("g") #=> "\x7F\xC0\x00\x00"</p>
<p>Wikipedia says:<br>
For example, a bit-wise IEEE floating-point standard single precision (32-bit) NaN would be: s111 1111 1axx xxxx xxxx xxxx xxxx xxxx where s is the sign (most often ignored in applications), a determines the type of NaN, and x is an extra payload (most often ignored in applications). If a = 1, it is a quiet NaN; if a is zero and the payload is nonzero, then it is a signaling NaN.</p>
<p>so it seems that the negation does it a bit wrong? i mean -@ should not change the value like that?</p> Ruby master - Feature #8987 (Open): map/collect extension which handles argumentshttps://bugs.ruby-lang.org/issues/89872013-10-05T23:02:50Zsowieso (So Wieso)sowieso@dukun.de
<p>Please consider extending map/collect by allowing additional arguments to be passed to proc, like:<br>
A: <code>[1,2,3,4].map :+, 4</code><br>
and/or<br>
B: <code>[1,2,3,4].map 4, &:+</code></p>
<p>=> [5, 6, 7, 8]</p>
<p>Variant A is probably more readable. Variant B is more versatile (allows arbitrary arguments to be passed to block).</p> Ruby master - Feature #8970 (Open): Array.zip and Array.producthttps://bugs.ruby-lang.org/issues/89702013-10-01T03:57:09Zsawa (Tsuyoshi Sawada)
<p>=begin<br>
Most of the time when I use <code>Array#zip</code> or <code>Array#product</code>, I feel cumbursome that I have to take out the first array and pass it as a receiver. For example, if I have</p>
<pre><code>a = [[:a, :b, :c], [:d, :e, :f], [:g, :h, :i]]
</code></pre>
<p>I have to do something like this:</p>
<pre><code>a.first.zip(*a.drop(1)){...}
a.first.product(*a.drop(1)){...}
</code></pre>
<p>Sometimes, the receiver (i.e., the first array) has significance, but most other times, that breaks asymmetry, making the code look ugly.</p>
<p>I would be happy if we had <code>Array.zip</code> and <code>Array.product</code> in addition so that we can do it like this:</p>
<pre><code>Array.zip(*a){...}
Array.product(*a){...}
</code></pre>
<p>=end</p> Ruby master - Feature #8967 (Open): add uninclude and unextend methodhttps://bugs.ruby-lang.org/issues/89672013-09-30T14:18:34Zwindwiny (wind winy)windwinyubt@gmail.com
<p>Can be add uninclude and unextend method to ruby core ?</p>
<p>That enable Klass include or prepend different module,<br>
make DECORATOR design pattern is easier.</p> Ruby master - Feature #8961 (Open): Synchronizable module to easily wrap methods in a mutexhttps://bugs.ruby-lang.org/issues/89612013-09-27T20:23:16Ztobiassvn (Tobias Svensson)
<p>=begin<br>
I propose a Synchronizable mixin to easily wrap methods in a mutex which works together with Ruby 2.1's method name symbols returned from '(({def}))'.</p>
<p>The Mixin adds a new '(({synchronized}))' class method which would alias the referenced method and redefines the original method wrapped in a '(({synchronize do .. end}))' block.</p>
<p>This is probably somewhat related and an alternative to <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: MutexedDelegator as a trivial way to make an object thread-safe (Rejected)" href="https://bugs.ruby-lang.org/issues/8556">#8556</a>.</p>
<hr>
<p>Proof of concept (I've used Monitor here so potential users won't have to worry about reentrancy):</p>
<p>require 'monitor'</p>
<p>module Synchronizable<br>
module ClassMethods<br>
def synchronized(method)<br>
aliased = :"#{method}_without_synchronization"<br>
alias_method aliased, method</p>
<pre><code> define_method method do |*args, &block|
monitor.synchronize do
__send__(aliased, *args, &block)
end
end
end
end
def monitor
@monitor ||= Monitor.new
end
def self.included(base)
base.extend(ClassMethods)
end
</code></pre>
<p>end</p>
<p>class Foo<br>
include Synchronizable</p>
<pre><code>synchronized def bar
# ...
end
</code></pre>
<p>end<br>
=end</p> Ruby master - Feature #8947 (Open): make alias, alias_method, attr_* return name of the aliashttps://bugs.ruby-lang.org/issues/89472013-09-24T21:34:52Zrkh (Konstantin Haase)me@rkh.im
<p>Now that def returns the method name, it would be handy to have alias/alias_method return the name of the alias:</p>
<p>class Foo<br>
private def foo() end<br>
protected alias_method :bar, :foo<br>
end</p>
<p>Same goes for the attr_* methods:</p>
<p>class Foo<br>
private attr_accessor :foo, :bar<br>
end</p>
<p>What do you think?</p> Ruby master - Feature #8921 (Open): Allow select, reject, etc to accept a regexhttps://bugs.ruby-lang.org/issues/89212013-09-18T23:37:00Zkyledecot (Kyle Decot)kyle.decot@icloud.com
<p>It would be handy if <code>select</code> could accept a regex. For example</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="sx">%w[foo bar baz]</span><span class="p">.</span><span class="nf">select</span><span class="p">(</span><span class="sr">/^ba/</span><span class="p">)</span> <span class="c1"># => ["bar", "baz"] </span>
</code></pre>
<p>This is currently possible via the slightly longer syntax</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="sx">%w[foo bar baz]</span><span class="p">.</span><span class="nf">select</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="p">[</span><span class="sr">/^ba/</span><span class="p">]}</span> <span class="c1"># => ["bar", "baz"] </span>
</code></pre> Ruby master - Feature #8896 (Open): #tap with missing blockhttps://bugs.ruby-lang.org/issues/88962013-09-11T19:05:44Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>In case when no block provided to tap, it fails. So if you want method which can be called with or without block - you can't do it like this:</p>
<p>def self.create(args={}, &block)<br>
new.set_attributes(args).tap(&block)<br>
end</p>
<p>but should use block_defined? to prevent #tap's failure.</p>
<p>I suggest to make tap with no block given just to return self and raise no errors.</p> Ruby master - Feature #8862 (Open): getoptlong to accept user-provided commandlinehttps://bugs.ruby-lang.org/issues/88622013-09-04T21:53:13Znoon (Fabrice Bauzac)libnoon@gmail.com
<p>=begin<br>
Hello,</p>
<p>The (({getoptlong})) module (({class GetoptLong})) provides no way for the user to provide a commandline that is not (({ARGV})). It appears that (({GetoptLong})) is tied to the (({ARGV})) global variable and this cannot be modified. The fine (({getoptlong})) algorithms are not reusable in particular situations where the command is not in (({ARGV})), short of performing some kind of hack to temporarily modify (({ARGV})).</p>
<p>This ticket requests the addition of a way to redirect a (({GetoptLong})) object to eat a different (({Array})) of (({String})) than (({ARGV})).</p>
<p>One way to implement this would be to change the getoptlong code to use (({@argv})) instead of (({ARGV})), set (({@argv})) to a copy of (({ARGV})) in (({#initialize})), and provide a (({#set_commandline(Array)})) method to set (({@argv})) to a copy of the argument.<br>
=end</p> Ruby master - Feature #8853 (Open): Should String#sub(pattern) returns an Enumerator?https://bugs.ruby-lang.org/issues/88532013-09-03T10:08:08Zokkez (okkez _)
<p>調べてみたのですが、過去に同様の議論があったのかどうかわからなかったので起票します。</p>
<p>以下のように String#sub(pattern) と使うと ArgumentError が発生します。</p>
<p>$ ruby -e "p ''.sub(//)"<br>
-e:1:in <code>sub': wrong number of arguments (1 for 2) (ArgumentError) from -e:1:in </code>'</p>
<p>一方、 String#gsub(pattern) だと Enumerator を返します。</p>
<p>$ ruby -e "p ''.gsub(//)"<br>
#<Enumerator: "":gsub(//)></p>
<p>RDoc ではこの挙動は説明されていませんでした。<br>
String#gsub(pattern)がEnumeratorを返すことについては書かれています。<br>
<a href="http://www.ruby-doc.org/core-2.0.0/String.html#method-i-sub" class="external">http://www.ruby-doc.org/core-2.0.0/String.html#method-i-sub</a><br>
<a href="http://www.ruby-doc.org/core-2.0.0/String.html#method-i-gsub" class="external">http://www.ruby-doc.org/core-2.0.0/String.html#method-i-gsub</a></p>
<p>一貫性の観点から考えると、String#sub(pattern)もEnumeratorを返した方が良いように思いましたがいかがでしょうか。<br>
まあ、String#sub だと置換は一回しか発生しないのでイマイチな感じはします。</p>
<ul>
<li>String#sub(pattern) が Enumerator を返すようになる</li>
<li>RDoc に String#gsub(pattern) と違って String#sub(pattern) が ArgumentError を発生させることの記述が追加される</li>
</ul>
<p>のどちらかが、満たされればいいと思っています。</p> Ruby master - Feature #8848 (Open): Syntax for binary stringshttps://bugs.ruby-lang.org/issues/88482013-08-31T15:59:43Zduerst (Martin Dürst)duerst@it.aoyama.ac.jp
<p>In commit 37486, Yui (Naruse) added a String#b method as proposed in <a href="http://bugs.ruby-lang.org/issues/6767" class="external">http://bugs.ruby-lang.org/issues/6767</a>.</p>
<p>String#b was added to allow easy generation of binary strings; this became necessary in particular after the source file encoding was changed to UTF-8.</p>
<p>However, as also recognized in <a href="http://bugs.ruby-lang.org/issues/6767" class="external">http://bugs.ruby-lang.org/issues/6767</a>, in the long term (ideally starting with Ruby 2.1) it would be better to make binary strings available as part of Ruby syntax.</p>
<p>One reason for this efficiency. String#b creates a duplicate object, which is not at all necessary for the frequent use case of String literals.</p>
<p>Another reason is encoding validity. To be able to e.g. create a "\xFF" binary string, with String#b in an UTF-8 source context, it is necessary to allow "\xFF" (temporarily at least) as an (actually invalid) UTF-8 string. This may be difficult for some implementations, and isn't desirable in general.</p>
<p>Regarding syntax, there are mainly two solutions:</p>
<ol>
<li>a '%b' prefix</li>
<li>a 'b' suffix</li>
</ol>
<p>The preferable syntax depends on the overall future approach of Ruby to String literal suffixes (see <a href="https://bugs.ruby-lang.org/issues/8579" class="external">https://bugs.ruby-lang.org/issues/8579</a>).</p> Ruby master - Feature #8834 (Open): Kernel#load_relativehttps://bugs.ruby-lang.org/issues/88342013-08-30T10:32:44Zsawa (Tsuyoshi Sawada)
<p>The intended difference between <code>Kernel#require</code> and <code>Kernel#load</code> is that the former is for external libraries and the latter is for Ruby scripts internal to the project. Considering this fact, <code>load</code> should be more likely than <code>require</code> to be used in a situation where you want to call a file through a relative path. Strangely, there is <code>Kernel#require_relative</code>, but no <code>Kernel#load_relative</code>. I request <code>Kernel#load_relative</code>. It is even more necessary than <code>Kernel#require_relative</code>.</p>
<p>It seems to me that people are using <code>Kernel#require_relative</code> when they want to use a relative path, even in the context where they are supposed to use <code>load</code> because of the lack of <code>Kernel#load_relative</code>. I don't think this is a good practice. Furthermore, in cases where you have a file without a <code>.rb</code> or other extention that you want to call via a relative path, there is no good way to do it.</p> Ruby master - Feature #8807 (Open): Custom literalshttps://bugs.ruby-lang.org/issues/88072013-08-21T18:20:52Ztrans (Thomas Sawyer)
<p>So why can't we define custom literals? There's been recent discussion about adding a new freeze literal. Would have been nice if coders could have defined it for themselves, then it would have been more clear if there really was enough use to add it to core.</p>
<p>I imagine the syntax of such a feature to be quite simple.</p>
<p>def %foo(string, mod=nil)<br>
p [string, mod]<br>
end</p>
<p>%foo{something}o<br>
=> ["something", "o"]</p> Ruby master - Feature #8804 (Open): ONCE syntaxhttps://bugs.ruby-lang.org/issues/88042013-08-20T11:45:48Zko1 (Koichi Sasada)
<p>How about to introduce ONCE{...} syntax which do block only once and return the first value?</p>
<ul>
<li>It is similar of BEGIN{} and END{}.</li>
<li>General syntax of /reg/o.</li>
</ul>
<a name="simulation-code"></a>
<h2 >simulation code<a href="#simulation-code" class="wiki-anchor">¶</a></h2>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="no">ONCE_CACHE</span> <span class="o">=</span> <span class="p">{}</span>
<span class="no">ONCE_MUTEX</span> <span class="o">=</span> <span class="no">Mutex</span><span class="p">.</span><span class="nf">new</span>
<span class="k">def</span> <span class="nf">ONCE</span><span class="p">(</span><span class="o">&</span><span class="n">b</span><span class="p">)</span>
<span class="k">raise</span> <span class="k">unless</span> <span class="nb">block_given?</span>
<span class="no">ONCE_MUTEX</span><span class="p">.</span><span class="nf">synchronize</span><span class="p">{</span>
<span class="n">key</span> <span class="o">=</span> <span class="nb">caller</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="mi">0</span><span class="p">]</span>
<span class="k">if</span> <span class="n">value</span> <span class="o">=</span> <span class="no">ONCE_CACHE</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="n">value</span>
<span class="k">else</span>
<span class="no">ONCE_CACHE</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="k">yield</span>
<span class="k">end</span>
<span class="p">}</span>
<span class="k">end</span>
<span class="mi">3</span><span class="p">.</span><span class="nf">times</span><span class="p">{</span><span class="o">|</span><span class="n">i</span><span class="o">|</span>
<span class="nb">p</span> <span class="no">ONCE</span><span class="p">{</span>
<span class="n">i</span> <span class="c1">#=> every time 0</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre>
<h2></h2>
<a name="Note-that-this-code-doesnt-work-if-two-or-more-ONCE-are-available-in-one-line"></a>
<h2 >Note that this code doesn't work if two or more ONCE{} are available in one line.<a href="#Note-that-this-code-doesnt-work-if-two-or-more-ONCE-are-available-in-one-line" class="wiki-anchor">¶</a></h2> Ruby master - Feature #8786 (Open): Process.clock_gettime(:realtime)https://bugs.ruby-lang.org/issues/87862013-08-15T22:33:13Zznz (Kazuhiro NISHIYAMA)
<p>Socket や IO#seek のように Process.clock_gettime の第一引数も Symbol で :realtime などを受け付けると良いのではないでしょうか。</p> Ruby master - Feature #8772 (Open): Hash alias #| merge, and the case for Hash and Array polymorp...https://bugs.ruby-lang.org/issues/87722013-08-11T11:46:03Ztrans (Thomas Sawyer)
<p>Ideally Hash and Array would be completely polymorphic in every manner in which it is possible for them to be so. The reason for this is very simple. It makes a programmer's life easier. For example, in a recent program I was working on, I had a list of keyboard layouts.</p>
<p>layouts = [layout1, layout2, layout3]</p>
<p>Later I realized I wanted to identify them by a label not an index. So...</p>
<p>layouts = {:foo => layout1, :bar => layout2, :baz => layout3}</p>
<p>Unfortunately this broke my program in a number of places, and I had to go through every use of <code>layouts</code> to translate what was an Array call into a Hash call. If Array and and Hash were more polymorphic I would have only had to adjust the places were I wanted to take advantage of the Hash. Ideally almost nothing should have actually broken.</p>
<p>The achieve optimal polymorphism between Hash and Array is to treat a Hash's keys as indexes and its values as as the values of an array. e.g.</p>
<p>a = [:a,:b,:c]<br>
h = {0=>:a,1=>:b,2=>:c}<br>
a.to_a #=> [:a,:b,:c]<br>
h.to_a #=> [:a,:b,:c]</p>
<p>Of course the ship has already sailed for some methods that are not polymorphic, in particular #each. Nonetheless it would still be wise to try to maximize the polymorphism going forward. (Perhaps even to be willing to take a bold leap in Ruby 3.0 to break some backward compatibility to improve upon this.)</p>
<p>In the mean time, let us consider what it might mean for Hash#+ as an alias for #merge, <em>if the above were so</em>:</p>
<p>([:a,:b] + [:c,:d]).to_a => [:a,:b,:c,:d]<br>
({0=>:a,1=>:b} + {2=>:c,3=>:d}).to_a => [:a,:b,:c,:d]</p>
<p>([:a,:b] + [:a,:b]).to_a => [:a,:b,:a,:b]<br>
({0=>:a,1=>:b} + {0=>:a,1=>:b}).to_a => [:a,:b]</p>
<p>Damn! So it appears that #+ isn't the right operator. Let's try #| instead.</p>
<p>([:a,:b] | [:c,:d]).to_a => [:a,:b,:c,:d]<br>
({0=>:a,1=>:b} | {2=>:c,3=>:d}).to_a => [:a,:b,:c,:d]</p>
<p>([:a,:b] | [:a,:b]).to_a => [:a,:b]<br>
({0=>:a,1=>:b} | {0=>:a,1=>:b}).to_a => [:a,:b]</p>
<p>Bingo. So I formally stand corrected. The best alias for merge is #| not #+.</p>
<p>Based on this line of reasoning I formally request the Hash#| be an alias of Hash#merge.</p>
<p>P.S. Albeit, given the current state of polymorphism between Ruby's Array and Hash, and the fact that it will probably never be improved upon, I doubt it really matters which operator is actually used.</p> Ruby master - Feature #8751 (Open): Add offsets to method#source_locationhttps://bugs.ruby-lang.org/issues/87512013-08-08T14:03:29Ztenderlovemaking (Aaron Patterson)tenderlove@ruby-lang.org
<p>Hello,</p>
<p>I would like to have byte offsets returned on the source_location for methods. For example:</p>
<p>def foo(&b)<br>
b.source_location # => [file_name, line_number, start_byte, end_byte]<br>
end</p>
<p>If we had the start and end byte for a method or proc, then we could find the source for methods and procs in each file. There are some cases (like with heredocuments) where the "end of the method" could be after the <code>end</code> keyword. But I think if we just have offsets for the start of <code>def</code> and the end of <code>end</code>, I think it would cover 99% of usecases.</p> Ruby master - Feature #8714 (Open): Non-interpolated regular expression literalhttps://bugs.ruby-lang.org/issues/87142013-08-01T08:07:19Zphluid61 (Matthew Kerwin)matthew@kerwin.net.au
<p>=begin</p>
<p>I propose a new %string for non-interpolated regexp literals: %R</p>
<p>It is common to see erroneous bug reports around the use of ((%#%)) in regexp literals, for example where (({/[$#]/})) raises a syntax error "unexpected $undefined", and this confuses people. The only solution is to rearrange the regular expression (such as (({/[$#]/}))), which is not always desirable.</p>
<p>An non-interpolated regexp, such as (({%R/[$#]/})), would allow a much simpler resolution.</p>
<p>=== Known Issues</p>
<ul>
<li>the capitalisation is the opposite of %Q(interpolated) and %q(uninterpolated)</li>
<li>%R was also proposed for literal Rationals in <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: Rational number literal (Closed)" href="https://bugs.ruby-lang.org/issues/8430">#8430</a>, although I believe this has been superseded by the (({1.2r})) syntax</li>
</ul>
<p>=end</p> Ruby master - Feature #8688 (Open): #sprintf should accept strings as keyshttps://bugs.ruby-lang.org/issues/86882013-07-26T02:33:03ZQuintus (Marvin Gülker)post+rubybugs@guelker.eu
<p>=begin<br>
Hi there,</p>
<p>Kernel#sprintf should support strings as keys. Currently it only works with symbols:</p>
<p>{irb(main):001:0> str = "This is %{foo}."<br>
=> "This is %{foo}."<br>
irb(main):002:0> sprintf(str, :foo => "bar")<br>
=> "This is bar."<br>
irb(main):003:0> sprintf(str, "foo" => "bar")<br>
KeyError: key{foo} not found<br>
from (irb):3:in <code>sprintf' from (irb):3 from /opt/rubies/mri/bin/irb:12:in </code>'}</p>
<p>ruby -v: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]</p>
<p>If I want a user to be able to enter format strings and (later) the corresponding parameter values, I don’t want to call #to_sym on the keys (because generating symbols from user input is known to cause memory issues).</p>
<p>Valete,<br>
Marvin</p>
<p>=end</p> Ruby master - Feature #8681 (Open): Net::HTTP should set TCP_NODELAY for requests with bodyhttps://bugs.ruby-lang.org/issues/86812013-07-25T03:40:34Znormalperson (Eric Wong)normalperson@yhbt.net
<p>Setting TCP_NODELAY to disable Nagle's algorithm speeds up successive writes which<br>
we use when sending HTTP PUT/POST requests with body.</p>
<p>From <a href="https://en.wikipedia.org/wiki/Nagle%27s_algorithm" class="external">https://en.wikipedia.org/wiki/Nagle%27s_algorithm</a></p>
<pre><code> The user-level solution is to avoid write-write-read sequences on
sockets. write-read-write-read is fine. write-write-write is
fine. But write-write-read is a killer. So, if you can, buffer up
your little writes to TCP and send them all at once. Using the
standard UNIX I/O package and flushing write before each read
usually works.
</code></pre>
<p>We currently hit the killer write-write-read case when sending requests<br>
with body using Net::HTTP</p>
<p>net-http-persistent does this by default (for all connections), even.<br>
I usually use net-http-persistent, but sometimes it's easier to use<br>
Net::HTTP on a new (bare) system and I've been bitten by this :x</p> Ruby master - Feature #8663 (Open): Officialy alias ArgumentError to ArgErrorhttps://bugs.ruby-lang.org/issues/86632013-07-23T00:07:56ZAnonymous
<p>When not using custom made exceptions, I find myself using TypeError, NameError and ArgumentError the most. ArgumentError is the longest and I would like to suggest to alias it officially as ArgError.</p> Ruby master - Feature #8640 (Open): Add Time#elapsed to return nanoseconds since creationhttps://bugs.ruby-lang.org/issues/86402013-07-16T03:39:06Ztenderlovemaking (Aaron Patterson)tenderlove@ruby-lang.org
<p>Hi,</p>
<p>We time many things in Rails (and so does lots of other code), and I've found that we spend lots of time allocating and subtracting time objects. For example:</p>
<p>start = Time.now</p>
<a name="do-stuff-we-want-to-time"></a>
<h2 >do stuff we want to time<a href="#do-stuff-we-want-to-time" class="wiki-anchor">¶</a></h2>
<p>finish = Time.now - start</p>
<p>It would be nice if we could just create one time object and grab the nanoseconds elapsed since the time object was created like so:</p>
<p>start = Time.now</p>
<a name="do-stuff-we-want-to-time-2"></a>
<h2 >do stuff we want to time<a href="#do-stuff-we-want-to-time-2" class="wiki-anchor">¶</a></h2>
<p>finished = start.elapsed # => nanoseconds elapsed.</p>
<p>I've attached a patch that implements this feature.</p> Ruby master - Feature #8635 (Open): attr_accessor with default blockhttps://bugs.ruby-lang.org/issues/86352013-07-14T23:59:56Zjudofyr (Magnus Holm)judofyr@gmail.com
<p>=begin</p>
<p>It's quite common to define attributes (like attr_reader, attr_accessor) with default values. It would be useful if Ruby provided a helper method for this case. attr_accessor and attr_reader can support this nicely using a default block:</p>
<p>class Person</p>
<a name="1-Simple-approach"></a>
<h1 >(1) Simple approach<a href="#1-Simple-approach" class="wiki-anchor">¶</a></h1>
<p>attr_writer :name<br>
def name<br>
@name ||= 'Hello'<br>
end</p>
<a name="2-nil-safe-approach"></a>
<h1 >(2) nil-safe approach<a href="#2-nil-safe-approach" class="wiki-anchor">¶</a></h1>
<p>attr_writer :name<br>
def name<br>
return @name if defined? @name<br>
@name = 'Hello'<br>
end</p>
<a name="3-This-proposal"></a>
<h1 >(3) This proposal<a href="#3-This-proposal" class="wiki-anchor">¶</a></h1>
<p>attr_accessor :name do<br>
'Hello'<br>
end<br>
end</p>
<p>p = Person.new<br>
p.instance_variable_get(:@name) # => nil<br>
p.name # => 'Hello'<br>
p.instance_variable_get(:@name) # => 'Hello'</p>
<p>Problems with current approaches:</p>
<ul>
<li>The reader and the writer looks widely different</li>
<li>Solution 1 doesn't work as intended when the default value may evaulate to nil/false</li>
<li>Solution 2 requires you to write the attribute name five times</li>
</ul>
<p>=end</p> Ruby master - Feature #8626 (Open): Add a Set coercion method to the standard lib: Set(possible_set)https://bugs.ruby-lang.org/issues/86262013-07-12T01:26:27Zsaturnflyer (Jim Gay)
<p>=begin<br>
I'd like to be able to take an object that may already be a Set (or not) and ensure that it is one</p>
<p>For example:</p>
<pre><code>set1 = Set.new
set2 = Set(set1)
set3 = Set(nil)
assert set1.equal?(set2)
assert_instance_of(Set, set3)
</code></pre>
<p>This is different from the behavior of Set.new in that it will return the same set rather than creating a new one</p>
<pre><code>set1 = Set.new
set2 = Set.new(set1) # <--- completely new object in memory
set2 = Set(set1) # <--- same object from memory
</code></pre>
<p>My thoughts about the implementation are simple:</p>
<pre><code>def Set(possible_set)
possible_set.is_a?(Set) ? possible_set : Set.new(possible_set)
end
</code></pre>
<p>I'm not sure if there are edge cases to unexpected behavior that I haven't thought of and I'm wondering if it ought to have a Set.try_convert as well<br>
=end</p> Ruby master - Feature #8619 (Open): Standard Profiling APIhttps://bugs.ruby-lang.org/issues/86192013-07-10T19:51:29Zyorickpeterse (Yorick Peterse)yorickpeterse@gmail.com
<p>At the time of writing there are many different Ruby implementations ranging<br>
from the common ones such as MRI, Jruby and Rubinius to slightly less common<br>
ones such as mruby and Topaz.</p>
<p>A recurring problem in all these implementations is that there's no standard<br>
API for profiling resource usage. For example, for MRI there's ruby-prof but in<br>
order to get garbage collection and memory usage related information you have<br>
to patch MRI. As far as I'm aware of Jruby is the only implementation that at<br>
this point offers proper tools for profiling your Ruby application as it piggy<br>
backs on top of the JVM and all the awesome profiling tools that come with it.</p>
<p>What I'd hereby like to propose is an API for all Ruby implementations that<br>
allows developers to profile at least the following:</p>
<ul>
<li>Garbage collection information</li>
<li>Memory usage</li>
<li>Object allocations</li>
</ul>
<p>These items are discussed in detail below.</p>
<a name="Topics"></a>
<h2 >Topics<a href="#Topics" class="wiki-anchor">¶</a></h2>
<a name="Garbage-Collection"></a>
<h3 >Garbage Collection<a href="#Garbage-Collection" class="wiki-anchor">¶</a></h3>
<p>In the past one would have to use REE or install a bunch of patches in order to<br>
get GC information such as when it would run, how many objects it processed,<br>
etc. What I'd like to see here is the following:</p>
<ul>
<li>When the GC starts/stops</li>
<li>How many objects are freed and how many are left intact</li>
<li>The time it takes for the GC to run</li>
</ul>
<p>If applicable there could be more added, this is just what I can think of from<br>
the top of my head.</p>
<a name="Memory-Usage"></a>
<h3 >Memory Usage<a href="#Memory-Usage" class="wiki-anchor">¶</a></h3>
<p>Next to the GC this is a particular important addition. Similar to GC<br>
information one would have to install MRI patches to get memory usage<br>
information or worse, use something along the lines of the following:</p>
<pre><code># Returns memory usage of the entire process in KB
def memory_usage
return `ps -o rss= #{Process.pid}`.strip.to_f
end
</code></pre>
<p>The above code is actually fairly common but also inaccurate and adds a pretty<br>
big overhead as a subshell has to be started for every call. It also wouldn't<br>
work on systems where <code>ps</code> is not available or would otherwise work<br>
differently.</p>
<p>Ideally one should be able to get the memory usage of individual memory calls<br>
similar to what you can now achieve using ruby-prof + a set of patches. This<br>
would greatly reduce the amount of time and effort required to hunt down memory<br>
leaks or otherwise memory intensive operations when it's not entirely clear why<br>
something is not performing as well as it should.</p>
<a name="Object-Allocations"></a>
<h3 >Object Allocations<a href="#Object-Allocations" class="wiki-anchor">¶</a></h3>
<p>This one goes a bit hand in hand with the memory usage topic. Ideally one<br>
should be able to get the amount of allocated objects per method call in a bit<br>
more accurage way than ObjectSpace currently provides. For example, it would be<br>
nice if one could see that method X allocated 2500 String objects, 2 Array<br>
Objects and 1 Foo::Bar object.</p>
<a name="API-Design"></a>
<h2 >API Design<a href="#API-Design" class="wiki-anchor">¶</a></h2>
<p>Code wise I'm not entirely sure how this would look, which is part of why I'm<br>
opening this feature request. I'm thinking out loud here but I was thinking of<br>
something along the lines of the following:</p>
<pre><code>require 'profiler/memory'
require 'profiler/allocations'
require 'profiler/gc'
# The same would be used for memory and allocation profiling but using
# different constants (e.g. MemoryProfiler and AllocationProfiler)
GC.enable_profiling
# Do some serious Ruby work here
# Here `result` would contain the profiling results per method call made
# since profiling was enabled.
result = GC.disable_profiling
</code></pre>
<p>The core idea however is that every Ruby implementation would offer the same<br>
public API (though the internals may differ). This way one could write a tool<br>
that for example displays a graph of the memory usage over time that would work<br>
in all the Ruby implementations. Currently this is not something that's<br>
possible due to the vastly different APIs (or total lack thereof).</p>
<p>Note that this request isn't a "I want this and I want it now" request but more<br>
the start of a discussion about such an API. The amount of time and effort<br>
required to get this to work on the various implementations could easily take<br>
months if not a few years (heavily depending on the amount of people<br>
available). Especially if you consider that some implementations might<br>
currently not even make the required information publically available.</p>
<p>So to cut a long story short: I hereby open the discussion on a common API for<br>
profiling resource usage in the varios Ruby implementations.</p>
<p>p.s. Although I'd also be interested in seeing execution time of methods and<br>
such I'm not entirely sure how I'd envision such an API. As such I've left it<br>
out of this request but of course everybody is welcome to discuss/include that<br>
as well.</p> Ruby master - Feature #8614 (Open): Object#singleton_class with a blockhttps://bugs.ruby-lang.org/issues/86142013-07-10T01:04:42Zsawa (Tsuyoshi Sawada)
<p>=begin<br>
Most of the time when I use <code>Object#singleton_class</code>, I use it with <code>class_eval</code> following it, like follows:</p>
<pre><code>class Foo
singleton_class.class_eval{attr_accessor :bar}
end
</code></pre>
<p>I think it would be convenient if <code>Object#singleton_class</code> can optionally take a block so that the following will mean the same as above.</p>
<pre><code>class Foo
singleton_class{attr_accessor :bar}
end
</code></pre>
<p>=end</p> Ruby master - Feature #8598 (Open): Expose information whether a timezone offset has been explici...https://bugs.ruby-lang.org/issues/85982013-07-03T20:27:06Zgpoul (Gerhard Poul)gerhard.poul@gmail.com
<p>For some applications it would be beneficial if Ruby would expose information on whether a DateTime object has an explicitly set timezone offset. An application might want to use DateTimes that don't concern themselves with timezone offsets and don't perform conversions between zones. To make this backwards compatible I'd suggest to expose a flag on whether an offset has been set or whether the default (offset=0) has been automatically assumed. An application might then decide to handle a DateTime that has the default timezone offset automatically assumed (offset=0) differently from a DateTime that has UTC (offset=0) set explicitly.</p> Ruby master - Feature #8570 (Open): Better mechanisms to safely load classes concurrentlyhttps://bugs.ruby-lang.org/issues/85702013-06-26T06:48:01Zheadius (Charles Nutter)headius@headius.com
<p>Today I had an issue reported under JRuby where a user was doing require "some library" unless defined?(SomeClassLibraryDefines). They were running into cases where threads hitting this logic concurrently might see a partially-initialized.</p>
<p>This pattern is not uncommon, and it is broken under <em>all</em> Ruby implementations. I believe this is a major flaw in the way Ruby makes classes visible, and we need to think about changes to how constants are defined during class init or come up with better options for concurrent loading. This bug offers a few ideas and experiments I've tried in hopes we can find something that will work.</p>
<p>The most basic problem is that the constant pointing at the class is set immediately upon opening the class. So the first option is:</p>
<ol>
<li>Do not define the constant until leaving the class/module body.</li>
</ol>
<p>This option would prevent concurrent threads from seeing an uninitialized class. In essence, this code:</p>
<p>class Foo<br>
def method1 ...<br>
def method2 ...<br>
end</p>
<p>would operated identically to this code:</p>
<p>Foo = Class.new do<br>
def method1 ...<br>
def method2 ...<br>
end</p>
<p>A defined? check on Foo would return false until the class was completely initialized, and lazily require + defined would work correctly.</p>
<p>However, there are pieces of code out there that depend on being able to access the constant from within the class/module body. This brings me to a second option I experimented with on JRuby:</p>
<ol start="2">
<li>Make the constant visible only to the defining thread until leaving the class/module body.</li>
</ol>
<p>In JRuby, I accomplished this by using Clojure's STM to implement the constant table. The beginning of opening a new class would start an STM transaction. The new, empty class body would be written into the constant table as part of the transaction, only visible to the current thread. Once the class body closed, the transaction would be committed and all code would see a complete class at that constant.</p>
<p>This version solves most issues with #1. The constant is available to that thread, so if code loading or class definition depends on the constant being available, it will still work. It prevents other threads from seeing a partially-initialized class. And it does not interrupt the normal flow of the program.</p>
<p>There are down sides, though, that may or may not happen in practice. If two threads try to start defining a class and it has never been defined before, only one will win. If code loading or class definition logic within the class/module spin up other threads, they won't be able to see the constant.</p>
<p>So then, perhaps we simply need a better mechanism to know if a given class is "complete" or not?</p>
<ol start="3">
<li>Add an attribute to Module indicating whether the class is "open" somewhere in the system.</li>
</ol>
<p>This would change the require check above to look more like this:</p>
<p>require 'some library' if !defined?(SomeLibrary) || SomeLibrary.open?</p>
<p>The logic here says "if SomeLibrary is not defined or is still being defined, attempt to do the require, which should block until done loading".</p>
<p>But this is somewhat ugly, so I have a fourth suggestion:</p>
<ol start="4">
<li>Add a new mechanism for concurrent requires that understands the services those requires provide.</li>
</ol>
<p>This would be something like:</p>
<p>require_service(:some_service_name, "some library")</p>
<p>This would behind the scenes perform checks for whether some_service_name was completely loaded as a service, and only define mark that service as "loaded" once the require had <em>completed</em>. This fixes all issues with all scenarios above. However, this basically ends up being:</p>
<p>require "some library" unless $".include?("some library")</p>
<p>...but with a user-provided name rather than the filename going into the equivalent of LOADED_FEATURES.</p>
<p>So...these are some brainstorming ideas. What do you think, Ruby world?</p> Ruby master - Feature #8566 (Open): [PATCH] Allow to configure additional preludeshttps://bugs.ruby-lang.org/issues/85662013-06-24T20:37:18Zvo.x (Vit Ondruch)v.ondruch@tiscali.cz
<p>Could you please accept the patch [1], which adds new '--with-prelude' configuration option. This configuration option allows to specify additional preludes and compile it into prelude.c, therefore execute the code on each start of Ruby.</p>
<p>= Rationale</p>
<p>In Fedora/RHEL/CentOS, there is ABRT tool [2], which allows to automatically report program failures. I developed abrt gem [3, 4], which adds support for catching of unhandled Ruby exceptions, this in turns help improve the quality of Fedora and software we ship.</p>
<p>Every Ruby programmer could require this gem and it would report the bugs, however, there is no way how to convince everybody, that they should use abrt gem. Therefore, it would make more sense, if the gem is automatically loaded by Ruby itself, when it is available on system. For that, I could patch Ruby, but I think somebody else could benefit from this feature as well, hence I am proposing this patch to upstream.</p>
<p>JFYI, Motohiro Kosaki once proposed to add ABRT support to Ruby [5], but I think it would be far better if Ruby knows nothing about ABRT by default and we could solve it on distribution level.</p>
<p>Thanks for considering.</p>
<p>[1] <a href="https://github.com/voxik/ruby/commit/efcca5238cf0804275e76d99a599190250d9dd0c" class="external">https://github.com/voxik/ruby/commit/efcca5238cf0804275e76d99a599190250d9dd0c</a><br>
[2] <a href="https://fedorahosted.org/abrt/" class="external">https://fedorahosted.org/abrt/</a><br>
[3] <a href="http://rubygems.org/gems/abrt" class="external">http://rubygems.org/gems/abrt</a><br>
[4] <a href="https://github.com/voxik/abrt-ruby" class="external">https://github.com/voxik/abrt-ruby</a><br>
[5] <a href="https://github.com/kosaki/ruby/commit/6283017dc2747f306808ce530292dc51273746ec" class="external">https://github.com/kosaki/ruby/commit/6283017dc2747f306808ce530292dc51273746ec</a></p> Ruby master - Feature #8564 (Open): Extend Module#attr... methodshttps://bugs.ruby-lang.org/issues/85642013-06-24T13:55:07ZAnonymous
<p>Extend #attr_reader, #attr_writer, #attr_accessor syntax to accept default values, such as:</p>
<pre><code>attr_reader foo: 42, bar: 43
</code></pre>
<p>Possibility of closures evaluated at initialization time might also be considered:</p>
<pre><code>attr_reader baz: -> { Time.now }, quux: 42
</code></pre> Ruby master - Feature #8544 (Open): OpenURI should open 'file://' URIshttps://bugs.ruby-lang.org/issues/85442013-06-19T23:35:21Zsilasdavis (Silas Davis)ruby-lang@silasdavis.net
<p>The following code prints the contents of '/tmp/file.txt':</p>
<p>require 'open-uri'<br>
open('/tmp/file.txt').read {|f| puts f.read }</p>
<p>which although useful should probably fail since a unix file path is not a URI, and therefore might shield data problems in a system</p>
<p>However the following should produce the same output and is a URI, but fails:</p>
<p>open('file:///tmp/file.txt').read {|f| puts f.read }</p>
<p>I note that the documentation for open-uri does explain that it is a wrapper for http, https, and ftp, but to deserve its name it should open such URIs as specified in this RFC: <a href="http://tools.ietf.org/html/rfc1630" class="external">http://tools.ietf.org/html/rfc1630</a>. This coupled with the fact that it already does open files, but not by a URI specification.</p> Ruby master - Feature #8494 (Open): Safe method for defensive copies. alternative to 'dup'https://bugs.ruby-lang.org/issues/84942013-06-05T16:26:27Zellipsoid (Andrew Northrop)andrew.northrop@gmail.com
<p>As a developer<br>
I want a simple method that will return a "safe" version of my object<br>
So I can make defensive copies easily and safely</p>
<p>This is related to issue 1844: <a href="http://www.ruby-forum.com/topic/3650325" class="external">http://www.ruby-forum.com/topic/3650325</a></p>
<p>I have tried using 'dup' to make defensive copies, but 'dup' throws an exception when used on a Fixnum and the like, because these values aren't copyable.</p>
<p>I tried to throw a "respond_to?" around the call, but that didn't work, since these classes still technically respond to 'dup'.</p>
<p>It looks like there's an extension method to do this (<a href="http://ruby-doc.org/gems/docs/c/core_ex-0.6.6.3/CoreEx/TryDup.html" class="external">http://ruby-doc.org/gems/docs/c/core_ex-0.6.6.3/CoreEx/TryDup.html</a>), but I don't see why this isn't in the core language. It seems like a common enough use case.</p>
<p>As far as naming, 'dup' is really just the means to an end. A more meaningful name would be something like 'defensive', or 'safe'. Although 'try_dup' like the extension method would also work.</p>
<p>Any chance of something like this making it in to Ruby core?</p> Ruby master - Feature #8478 (Open): The hash returned by Enumerable#group_by should have an empty...https://bugs.ruby-lang.org/issues/84782013-06-03T04:37:46Zphiggins (Pete Higgins)pete@peterhiggins.org
<p>Without this patch, nil checks might need to be done on the return value of Enumerable#group_by:</p>
<p>$ cat test_group_by.rb<br>
a = [1, 2, 3, "a", "b"]<br>
g = a.group_by {|o| o.class }</p>
<p>puts "Fixnums: #{g[Fixnum].size}"<br>
puts "Strings: #{g[String].size}"<br>
puts "Arrays: #{g[Array].size}"</p>
<p>$ ruby test_group_by.rb<br>
Fixnums: 3<br>
Strings: 2<br>
test_group_by.rb:6:in <code><main>': undefined method </code>size' for nil:NilClass (NoMethodError)</p>
<p>This patch adds a default value of an empty array to the hash returned by Enumerable#group_by, so the script above will work:</p>
<p>$ ./ruby -I.:lib test_group_by.rb<br>
Fixnums: 3<br>
Strings: 2<br>
Arrays: 0</p> Ruby master - Feature #8452 (Open): Kernel#otherwise to rewrite code like (obj || default_obj).do...https://bugs.ruby-lang.org/issues/84522013-05-26T20:41:57Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>Imagine you have code like this<br>
(long_computation_chain || []).do_smth<br>
While it isn't difficult, but it forces a developer to use additional parentheses. It can be difficult to trace where opening bracket is when computation_chain is long. Due to this idiom code cannot be read or written left to right. This is the same problem as for<br>
Hash[ *long_computation ]</p>
<p>So I propose a simple method Kernel#otherwise</p>
<pre><code>def otherwise(value, check = nil)
if !check
self || value
else
check.to_proc.call(self) ? self : value
end
end
</code></pre>
<p>So now one can write:<br>
long_computation_chain.otherwise([]).do_smth<br>
or<br>
long_computation_chain.otherwise('default', :empty?).do_smth<br>
or<br>
long_computation_chain.otherwise('numbers not allowed', ->(x){ x.grep(/\d+/) }).do_smth</p> Ruby master - Feature #8449 (Open): Array#ary_plus always returns an arrayhttps://bugs.ruby-lang.org/issues/84492013-05-25T19:48:03Ztxemagon (José M. González)txema.gonz@gmail.com
<p>=begin</p>
<p>Even when Array is subclassified, + operator keeps on returning an Array.</p>
<p>Don't know if it is a bug or intentional, but it has surprised me for sure.</p>
<p>I paste some code for demonstrational purposes:</p>
<p>#!/usr/bin/env ruby<br>
#ary_plus.rb</p>
<a name="Shows-an-unexpected-behavior-to-me"></a>
<h1 >Shows an unexpected behavior to me<a href="#Shows-an-unexpected-behavior-to-me" class="wiki-anchor">¶</a></h1>
<a name="when-adding-Array-subclasess"></a>
<h1 >when adding Array subclasess.<a href="#when-adding-Array-subclasess" class="wiki-anchor">¶</a></h1>
<p>class Subarray < Array; end</p>
<p>a = Subarray.new<br>
b = Subarray.new</p>
<p>result = a + b</p>
<a name="I-was-expecting-to-have-a-Subarray-back"></a>
<h1 >I was expecting to have a Subarray back<a href="#I-was-expecting-to-have-a-Subarray-back" class="wiki-anchor">¶</a></h1>
<p>unless result.is_a? Subarray<br>
puts "result is not a [Subarray]"<br>
end</p>
<p>puts "result variable is a [#{result.class.name}]"</p>
<p>=end</p> Ruby master - Bug #8444 (Open): Regexp vars $~ and friends are not thread localhttps://bugs.ruby-lang.org/issues/84442013-05-24T18:15:17Zjamespharaoh (James Pharaoh)james@phsys.co.uk
<p>In the docs for the Regexp special variables, <code>$~</code> and friends, it says "These global variables are thread-local and method-local variables". However the following gives an unexpected result:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">def</span> <span class="nf">get_proc</span>
<span class="nb">proc</span> <span class="k">do</span> <span class="o">|</span><span class="n">str</span><span class="o">|</span>
<span class="n">str</span> <span class="o">=~</span> <span class="sr">/(.+)/</span>
<span class="nb">sleep</span> <span class="mf">0.1</span>
<span class="nb">puts</span> <span class="s2">"got </span><span class="si">#{</span><span class="vg">$1</span><span class="si">}</span><span class="s2"> from </span><span class="si">#{</span><span class="n">str</span><span class="si">}</span><span class="se">\n</span><span class="s2">"</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="nb">proc</span> <span class="o">=</span> <span class="n">get_proc</span>
<span class="n">t1</span> <span class="o">=</span> <span class="no">Thread</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="nb">proc</span><span class="p">.</span><span class="nf">call</span> <span class="s2">"abc"</span> <span class="p">}</span>
<span class="n">t2</span> <span class="o">=</span> <span class="no">Thread</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="nb">proc</span><span class="p">.</span><span class="nf">call</span> <span class="s2">"def"</span> <span class="p">}</span>
<span class="n">t1</span><span class="p">.</span><span class="nf">join</span>
<span class="n">t2</span><span class="p">.</span><span class="nf">join</span>
</code></pre>
<p>This outputs the following:</p>
<pre><code>got abc from abc
got abc from def
</code></pre>
<p>The expected result is of course:</p>
<pre><code>got abc from abc
got def from def
</code></pre>
<p>Clearly the variables are being scoped to the <code>get_proc</code> method and are being shared by both threads. This runs contrary to the documentation and also to expectations.</p>
<p>This behaviour should either be changed, or the documentation updated to reflect the actual behaviour.</p>
<p>Interestingly, the following does work as expected:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">proc</span> <span class="o">=</span> <span class="nb">proc</span> <span class="k">do</span> <span class="o">|</span><span class="n">str</span><span class="o">|</span>
<span class="n">str</span> <span class="o">=~</span> <span class="sr">/(.+)/</span>
<span class="nb">sleep</span> <span class="mf">0.1</span>
<span class="nb">puts</span> <span class="s2">"got </span><span class="si">#{</span><span class="vg">$1</span><span class="si">}</span><span class="s2"> from </span><span class="si">#{</span><span class="n">str</span><span class="si">}</span><span class="se">\n</span><span class="s2">"</span>
<span class="k">end</span>
<span class="n">t1</span> <span class="o">=</span> <span class="no">Thread</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="nb">proc</span><span class="p">.</span><span class="nf">call</span> <span class="s2">"abc"</span> <span class="p">}</span>
<span class="n">t2</span> <span class="o">=</span> <span class="no">Thread</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="nb">proc</span><span class="p">.</span><span class="nf">call</span> <span class="s2">"def"</span> <span class="p">}</span>
<span class="n">t1</span><span class="p">.</span><span class="nf">join</span>
<span class="n">t2</span><span class="p">.</span><span class="nf">join</span>
</code></pre> Ruby master - Feature #8437 (Open): custom operators, unicodehttps://bugs.ruby-lang.org/issues/84372013-05-23T09:20:16Zeike.rb (Eike Dierks)eike@inter.net
<p>The ruby language does currently one support a predefined set of operators.<br>
It would be nice to add custom operators.<br>
A lot of people ask about the elvis operator aka (?:) to cope with nil, aka rails try()</p>
<p>This probably is a problem with the parser at first,<br>
because introducing new operators makes parsing a lot more complicated.</p>
<p>Maybe we could allow symbols from the unicode space<br>
to be used as new operators?<br>
That would be compatible with all before code written in ascii.</p>
<p>So we could allow all the symbols from the unicode Math operators plane<br>
to be available as operators in Ruby.</p>
<p>While few of you might have tried that,<br>
Unicode is fully available for naming identifiers.</p>
<p>We should also extend the set of operators to the unicode space.</p>
<p>While we are still not used to it now,<br>
to have some unicode characters in our codes,<br>
could really add to the expressivness.</p>
<p>So as of today, you can already name your variable like<br>
delta_t or Δt</p>
<p>Or if you're working with angles,<br>
you might call your variables α or Θ<br>
This is completely legal in Ruby.</p>
<p>I'm asking for:<br>
this_set ∪ other_set</p>
<p>or maybe we could even do this for prefix like:<br>
√2</p>
<p>I'd believe the math operator plane of unicode should be removed<br>
from the allowable names of identifiers,<br>
but should instead be reserved for operators in the parser, like + nowdays is.</p> Ruby master - Feature #8404 (Open): virtual, hooked or read only global variabels for ruby only c...https://bugs.ruby-lang.org/issues/84042013-05-14T21:19:29ZHanmac (Hans Mackowiak)hanmac@gmx.de
<p>currently pure virtual or hooked global variables can only be defined with cFunctions like rb_define_virtual_variable</p>
<p>i think it would be cool if this would be possible in Ruby code too</p> Ruby master - Feature #8366 (Open): Exception.message take time to execute depending on the insta...https://bugs.ruby-lang.org/issues/83662013-05-04T08:11:37Zanuraguniyal (anurag uniyal)anuraguniyal@gmail.com
<p>I am seeing very interesting and catastrophic behavior with ruby, see the code below</p>
<pre><code>class ExceptionTest
def test
@result = [0]*500000
begin
no_such_method
rescue Exception => ex
puts "before #{ex.class}"
st = Time.now
ex.message
puts "after #{Time.now-st} #{ex.message}"
end
end
end
ExceptionTest.new.test
</code></pre>
<p>Ideally ex.message should not take any time to execute and hence Time taken should be in ms, but here is the output</p>
<pre><code>ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.4.2]
before NameError
after 0.462443 undefined local variable or method `no_such_method' for #<ExceptionTest:0x007fc74a84e4f0>
</code></pre>
<p>If I assign <code>[0]*500000</code> to a local variable instead of instance variable e.g. <code>result = [0]*500000</code> it runs as expected</p>
<pre><code>ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.4.2]
before NameError
after 2.8e-05 undefined local variable or method `no_such_method' for #<ExceptionTest:0x007ff59204e518>
</code></pre>
<p><strong>It looks like somehow <code>ex.message</code> is looping thru the instance variables, why it would do so, please enlighten me!</strong></p>
<p>I have tried it on ruby ruby-1.9.2-p290, ruby-1.9.1-p376 and whatever version the ruby on codepad.org is.</p> Ruby master - Feature #8321 (Open): Ripper: I would like coordinates for keywordshttps://bugs.ruby-lang.org/issues/83212013-04-25T08:10:04Zericp (Eric Promislow)eric.promislow@gmail.com
<p>=begin<br>
Ripper gives the (({[line, column]})) coordinates for identifiers, strings, and numbers.</p>
<p>I would like it if it appended those coordinates to most of the block keywords,<br>
including (({:program})), (({:if})), (({:while})), (({:unless})), (({:end})), (({:def})), (({:class})), (({:module})), etc. As with the<br>
identifiers, it should go at the end. So an (({if}))-block would be represented as<br>
[0] :if<br>
[1] CONDITION<br>
[2] BLOCK<br>
[3] [:elsif, ...] || [:else, ...] || nil<br>
[4] [lineNo, colNo] # location of the leading :if/:elsif/:else/:unless</p>
<p>I currently get the first coordinate of ((%CONDITION%)), and then look up the preceding<br>
(({:if}))/(({:elsif}))/(({:else})) using (({Ripper.lex(src).find_all{|posn kwd name| kwd == :on_kw && %w/if else elsif/.include?(name) }}))</p>
<p>So the info is in Ripper. It would be more convenient if I could get that info in the src tree.</p>
<p>Note that my suggestion won't break (most) existing code, as the new data goes at the end<br>
of the list.</p>
<p>The same would be useful for other keywords, including (({:module})) (({:class})) (({:def})) (({:try})) (({:catch})) (({:begin})) (({:rescue})).<br>
=end</p> Ruby master - Feature #8291 (Open): Allow retrieving the root Fiber of a Threadhttps://bugs.ruby-lang.org/issues/82912013-04-19T15:53:51Zhalorgium (Tim Carey-Smith)ruby@spork.in
<p>=begin<br>
Currently (({Thread.backtrace})) returns the stack frames for the currently running (({Fiber})).<br>
It is not possible to retrieve the backtrace.</p>
<p>Building on <a href="http://bugs.ruby-lang.org/issues/8263" class="external">http://bugs.ruby-lang.org/issues/8263</a>, this would allow for this feature.<br>
=end</p> Ruby master - Feature #8275 (Open): Add Module#public_const_gethttps://bugs.ruby-lang.org/issues/82752013-04-16T18:28:56Zrkh (Konstantin Haase)me@rkh.im
<p>Right now, <code>const_get</code> will always return a constant, no matter the visibility, which is probably what we want most of the time. But if you for instance have code that does some automatic name to constant resolution, you might now want to leak private constants.</p>
<p>module Foo<br>
Bar = 42<br>
private_constant :Bar<br>
end</p>
<a name="currently"></a>
<h1 >currently:<a href="#currently" class="wiki-anchor">¶</a></h1>
<p>Foo::Bar # raises NameError<br>
Foo.const_get("Bar") # => 42<br>
Object.const_get("Foo::Bar") # => 42</p>
<a name="proposed"></a>
<h1 >proposed:<a href="#proposed" class="wiki-anchor">¶</a></h1>
<p>Foo.public_const_get("Bar") # raises NameError<br>
Object.public_const_get("Foo::Bar") # raises NameError</p> Ruby master - Feature #8272 (Open): Transfer feature tracking to CommonRubyhttps://bugs.ruby-lang.org/issues/82722013-04-16T05:45:34Zheadius (Charles Nutter)headius@headius.com
<p>If my proposal in <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: Proposal for moving to a more visible, formal process for feature requests (Assigned)" href="https://bugs.ruby-lang.org/issues/8271">#8271</a> is accepted, we'll need to:</p>
<ol>
<li>
<p>Document in appropriate places that CommonRuby is the place to file and track feature changes. Examples of such places: bugs.ruby-lang.org top-level page, pages for the existing "trunk" and version-specific Redmine projects, ruby-lang.org pages that describe how to file bugs.</p>
</li>
<li>
<p>Decide how to handle the "feature" flag in the current trackers. This may include solutions like removing it entirely (perhaps infeasible if existing features are not migrated to CommonRuby), adding a warning or error when "feature" is selected to encourage users to file under CommonRuby instead, or automatically putting "feature" issues under CommonRuby at submission time.</p>
</li>
<li>
<p>(optional) Migrate existing open features to CommonRuby.</p>
</li>
</ol> Ruby master - Feature #8270 (Open): Ruby should build without thread support (aka minix)https://bugs.ruby-lang.org/issues/82702013-04-16T04:04:28Zeike.rb (Eike Dierks)eike@inter.net
<p>I tried to ./configure ruby on Minix 3.2.1,<br>
The configure failed, because minix does not yet implement threads.</p>
<p>I'd like to suggest that ruby should still build on platforms without threads.</p>
<p>AFAIK the language does not yet require thread support in itself,<br>
but maybe the new GC does require it.<br>
So we might want to look up,<br>
where the dependencies on threading really are.</p> Ruby master - Feature #8259 (Open): Atomic attributes accessorshttps://bugs.ruby-lang.org/issues/82592013-04-12T17:43:20Zfunny_falcon (Yura Sokolov)funny.falcon@gmail.com
<p>Motivated by this gist ((<a href="URL:https://gist.github.com/jstorimer/5298581" class="external">URL:https://gist.github.com/jstorimer/5298581</a>)) and atomic gem</p>
<p>I propose Class.attr_atomic which will add methods for atomic swap and CAS:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="k">class</span> <span class="nc">MyNode</span>
<span class="nb">attr_accessor</span> <span class="ss">:item</span>
<span class="n">attr_atomic</span> <span class="ss">:successor</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">successor</span><span class="p">)</span>
<span class="vi">@item</span> <span class="o">=</span> <span class="n">item</span>
<span class="vi">@successor</span> <span class="o">=</span> <span class="n">successor</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">node</span> <span class="o">=</span> <span class="no">MyNode</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">other_node</span><span class="p">)</span>
<span class="c1"># attr_atomic ensures at least #{attr} reader method exists. May be, it should</span>
<span class="c1"># be sure it does volatile access.</span>
<span class="n">node</span><span class="p">.</span><span class="nf">successor</span>
<span class="c1"># #{attr}_cas(old_value, new_value) do CAS: atomic compare and swap</span>
<span class="k">if</span> <span class="n">node</span><span class="p">.</span><span class="nf">successor_cas</span><span class="p">(</span><span class="n">other_node</span><span class="p">,</span> <span class="n">new_node</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">"there were no interleaving with other threads"</span>
<span class="k">end</span>
<span class="c1"># #{attr}_swap atomically swaps value and returns old value.</span>
<span class="c1"># It ensures that no other thread interleaves getting old value and setting</span>
<span class="c1"># new one by cas (or other primitive if exists, like in Java 8)</span>
<span class="n">node</span><span class="p">.</span><span class="nf">successor_swap</span><span class="p">(</span><span class="n">new_node</span><span class="p">)</span>
</code></pre>
<p>It will be very simple for MRI cause of GIL, and it will use atomic primitives for<br>
other implementations.</p>
<p>Note: both (({#{attr}_swap})) and (({#{attr}_cas})) should raise an error if instance variable were not explicitly set before.</p>
<p>Example for nonblocking queue: ((<a href="URL:https://gist.github.com/funny-falcon/5370416" class="external">URL:https://gist.github.com/funny-falcon/5370416</a>))</p>
<p>Something similar should be proposed for Structs. May be override same method as (({Struct.attr_atomic}))</p>
<p>Open question for reader:<br>
should (({attr_atomic :my_attr})) ensure that #my_attr reader method exists?<br>
Should it guarantee that (({#my_attr})) provides 'volatile' access?<br>
May be, (({attr_reader :my_attr})) already ought to provide 'volatile' semantic?<br>
May be, semantic of (({@my_attr})) should have volatile semantic (i doubt for that)?</p> Ruby master - Feature #8232 (Open): Rudiments of abstract algebra in Rubyhttps://bugs.ruby-lang.org/issues/82322013-04-07T18:25:12ZAnonymous
<p>I have recently been struggling with Matrix class to make it accept physical magnitudes for matrix multiplication, and at that opportunity (<a href="http://bugs.ruby-lang.org/issues/8223" class="external">http://bugs.ruby-lang.org/issues/8223</a>), I noticed that rings and fields in Ruby do not know their additive identity. Eg. there is no method Float#zero or Rational#zero... I therefore propose that:</p>
<ol>
<li>every ring has #additive_identity, alias #zero method defined.</li>
<li>every ring has other methods defined, as required for rings in abstract algebra. An example (perhaps a stupid example) might be:</li>
</ol>
<p>class << Integer<br>
def additive_identity; 0 end<br>
alias zero additive_identity<br>
def add( other ); self + other end<br>
def additive_inverse; -self end<br>
def multiply( other ); self * other end<br>
def multiplicative_identity; 1 end<br>
end</p>
<ol start="3">
<li>That every field in Ruby has, in addition to the above methods, a method #multiplicative_inverse defined, as in:</li>
</ol>
<p>class << Float<br>
def additive_identity; 0.0 end<br>
alias zero additive_identity<br>
def add( other ); self + other end<br>
def additive_inverse; -self end<br>
def multiply( other ); self * other end<br>
def multiplicative_identity; 1.0 end<br>
alias one multiplicative_identity<br>
def multiplicative_inverse; 1.0 / self end<br>
end</p>
<p>I am no pro mathematician, and abstract algebra first sounded to me like a kind of thing that should be treated in some specialized libraries for math nerds, but looking how Twitter pays people to write abstract algebra in Scala</p>
<p><a href="https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Monoid.scala" class="external">https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Monoid.scala</a></p>
<p>and reading posts like this one about it:</p>
<p><a href="http://stackoverflow.com/questions/14790588/what-is-twitters-interest-in-abstract-algebra" class="external">http://stackoverflow.com/questions/14790588/what-is-twitters-interest-in-abstract-algebra</a></p>
<p>, where especially noteworthy comment is that by Randall Schulz of box.com, fourth from the top.</p>
<p>If we actually require Ruby rings and fields to have the basic properties of rings and fields (just like Enumerable classes are required to have #each method), it would be possible to implement structured objects such as Matrices over them, and instead of intuitively using numeric literals such as 0 and 1, the matrix or another structured object would ask rings / fields, which their elements come from, what their #additive_identity (#zero), #multiplicative_identity (#one) is. And at the same time, I would like to express my wish that Matrix be made a standard part of Ruby, that does not need to be loaded by require.</p> Ruby master - Feature #8229 (Open): extend Hash.include?https://bugs.ruby-lang.org/issues/82292013-04-07T08:14:09Zeike.rb (Eike Dierks)eike@inter.net
<p>I'd like to suggest to extend the Hash.include? method.</p>
<p>Currently Hash.include? can only be used to ask for a key,<br>
I believe it should be extended to ask for a (key value) pair.</p>
<p>I believe this extension can be done without breaking prior api.</p>
<p>I suggest to extend the signature of Hash.include?<br>
to Hash.include?(key, value)</p>
<p>That message should return true,<br>
if the receiving object does have an object at key which is equal to value.</p>
<p>It would be a simple replacement for:<br>
h.include?(key) && h[key] == value</p>
<p>But I do not want to stop there.<br>
I'm heading for h.include_all?(other_hash)<br>
and h.include_any?(other_hash)</p>
<p>and it would be valuable to have h.intersect(other_hash) etc</p>
<p>I believe these to be useful primitives when working with hashes.</p>
<p>I'd like to have the api of the Set class available for the Hash class as well,<br>
but there working on key/value matching.</p>
<p>Obviously any change to such the substantial class as the Hash class<br>
needs a lot of thought for compatibility.</p>
<p>But I believe this can be done without breaking any prior code,<br>
and it could add a lot of new out of the box functionality.</p>
<p>This probably needs some more thought.<br>
We might come up with some dsl like thing like<br>
h.includes.any? or h.includes.all? or h.includes.none?<br>
to be used cross all collection classes.</p>
<p>Someone must be in charge for the Hash class,<br>
my 2p</p> Ruby master - Feature #8206 (Open): Should Ruby core implement String#blank? https://bugs.ruby-lang.org/issues/82062013-04-03T09:32:10Zsam.saffron (Sam Saffron)sam.saffron@gmail.com
<p>There has been some discussion about porting the <code>#blank?</code> protocol over to Ruby in the past that has been rejected by Matz.</p>
<p>This proposal is only about <code>String</code> however.</p>
<p>At the moment to figure out if you have a blank string you would</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="s2">" "</span><span class="p">.</span><span class="nf">strip</span><span class="p">.</span><span class="nf">length</span> <span class="o">==</span> <span class="mi">0</span>
</code></pre>
<p>The disadvantage is that this forces unneeded allocations and does too much work:</p>
<p>An optimal implementation would be:</p>
<pre><code class="c syntaxhl" data-language="c"><span class="k">static</span> <span class="n">VALUE</span>
<span class="nf">rb_str_blank</span><span class="p">(</span><span class="n">VALUE</span> <span class="n">str</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">rb_encoding</span> <span class="o">*</span><span class="n">enc</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">s</span><span class="p">,</span> <span class="o">*</span><span class="n">e</span><span class="p">;</span>
<span class="n">enc</span> <span class="o">=</span> <span class="n">STR_ENC_GET</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">RSTRING_PTR</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">s</span> <span class="o">||</span> <span class="n">RSTRING_LEN</span><span class="p">(</span><span class="n">str</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="n">Qtrue</span><span class="p">;</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">RSTRING_END</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="k">while</span> <span class="p">(</span><span class="n">s</span> <span class="o"><</span> <span class="n">e</span><span class="p">)</span> <span class="p">{</span>
<span class="kt">int</span> <span class="n">n</span><span class="p">;</span>
<span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">cc</span> <span class="o">=</span> <span class="n">rb_enc_codepoint_len</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">e</span><span class="p">,</span> <span class="o">&</span><span class="n">n</span><span class="p">,</span> <span class="n">enc</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">rb_isspace</span><span class="p">(</span><span class="n">cc</span><span class="p">)</span> <span class="o">&&</span> <span class="n">cc</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="n">Qfalse</span><span class="p">;</span>
<span class="n">s</span> <span class="o">+=</span> <span class="n">n</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">Qtrue</span><span class="p">;</span>
<span class="p">}</span>
</code></pre>
<p>This in turn is about 5-8x than the regex solution to the problem and way faster than allocating one massive string with strip when length is large.</p>
<p>Should Ruby take on this method, to accompany <code>#strip</code> following its practice.</p>
<hr>
<p>A slight caveat though is that active support has a somewhat different definition of blank?</p>
<pre><code class="c syntaxhl" data-language="c"><span class="k">const</span> <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">as_blank</span><span class="p">[</span><span class="mi">26</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="mi">9</span><span class="p">,</span> <span class="mh">0xa</span><span class="p">,</span> <span class="mh">0xb</span><span class="p">,</span> <span class="mh">0xc</span><span class="p">,</span> <span class="mh">0xd</span><span class="p">,</span>
<span class="mh">0x20</span><span class="p">,</span> <span class="mh">0x85</span><span class="p">,</span> <span class="mh">0xa0</span><span class="p">,</span> <span class="mh">0x1680</span><span class="p">,</span> <span class="mh">0x180e</span><span class="p">,</span> <span class="mh">0x2000</span><span class="p">,</span> <span class="mh">0x2001</span><span class="p">,</span>
<span class="mh">0x2002</span><span class="p">,</span> <span class="mh">0x2003</span><span class="p">,</span> <span class="mh">0x2004</span><span class="p">,</span> <span class="mh">0x2005</span><span class="p">,</span> <span class="mh">0x2006</span><span class="p">,</span> <span class="mh">0x2007</span><span class="p">,</span> <span class="mh">0x2008</span><span class="p">,</span>
<span class="mh">0x2009</span><span class="p">,</span> <span class="mh">0x200a</span><span class="p">,</span> <span class="mh">0x2028</span><span class="p">,</span> <span class="mh">0x2029</span><span class="p">,</span> <span class="mh">0x202f</span><span class="p">,</span> <span class="mh">0x205f</span><span class="p">,</span> <span class="mh">0x3000</span>
<span class="p">};</span>
<span class="k">static</span> <span class="n">VALUE</span>
<span class="nf">rb_str_blank_as</span><span class="p">(</span><span class="n">VALUE</span> <span class="n">str</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">rb_encoding</span> <span class="o">*</span><span class="n">enc</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">s</span><span class="p">,</span> <span class="o">*</span><span class="n">e</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">i</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">found</span><span class="p">;</span>
<span class="n">enc</span> <span class="o">=</span> <span class="n">STR_ENC_GET</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">RSTRING_PTR</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">s</span> <span class="o">||</span> <span class="n">RSTRING_LEN</span><span class="p">(</span><span class="n">str</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="n">Qtrue</span><span class="p">;</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">RSTRING_END</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="k">while</span> <span class="p">(</span><span class="n">s</span> <span class="o"><</span> <span class="n">e</span><span class="p">)</span> <span class="p">{</span>
<span class="kt">int</span> <span class="n">n</span><span class="p">;</span>
<span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">cc</span> <span class="o">=</span> <span class="n">rb_enc_codepoint_len</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">e</span><span class="p">,</span> <span class="o">&</span><span class="n">n</span><span class="p">,</span> <span class="n">enc</span><span class="p">);</span>
<span class="n">found</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span><span class="p">(</span><span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o"><</span><span class="mi">26</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
<span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">current</span> <span class="o">=</span> <span class="n">as_blank</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
<span class="k">if</span><span class="p">(</span><span class="n">current</span> <span class="o">==</span> <span class="n">cc</span><span class="p">)</span> <span class="p">{</span>
<span class="n">found</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">break</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">if</span><span class="p">(</span><span class="n">cc</span> <span class="o"><</span> <span class="n">current</span><span class="p">){</span>
<span class="k">break</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">found</span><span class="p">)</span> <span class="k">return</span> <span class="n">Qfalse</span><span class="p">;</span>
<span class="n">s</span> <span class="o">+=</span> <span class="n">n</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">Qtrue</span><span class="p">;</span>
<span class="p">}</span>
</code></pre>
<p>Clearly it makes no sense to have such a method.</p>
<p>If Ruby took over implementing <code>String#blank?</code> it would clash with Active Support. But imho would enforce better API consistency.</p>
<p>Thoughts?</p> Ruby master - Bug #8185 (Open): Thread/fork issuehttps://bugs.ruby-lang.org/issues/81852013-03-30T03:33:57ZAnonymous
<p>Hello all,</p>
<p>I've found an issue where calling fork inside a thread, and passing a block<br>
to the fork, causes the forked process to continue after the block. I've<br>
reproduced the issue on the following versions of ruby:<br>
ruby 2.0.0p100 (2013-03-27 revision 39954) [x86_64-darwin10.8.0]<br>
ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin10.8.0]</p>
<p>Here is the script I used to reproduce:</p>
<p>1000.times do |j|<br>
puts "run #{j}"<br>
threads = []<br>
100.times do |i|<br>
threads << Thread.new(i) do |local_i|<br>
opid = fork do<br>
# exit!(true) # fixes the issue<br>
# exit(true) # doesn't fix the issue<br>
# no 'exit' also exhibits issue<br>
end<br>
::Process.waitpid(opid, 0)<br>
File.open("/tmp/test_thread_fork_#{local_i}.pid", "w") {|f| f.write<br>
"1" }<br>
end<br>
end<br>
threads.map { |t| t.join }</p>
<p>borked = false<br>
100.times do |i|<br>
fn = "/tmp/test_thread_fork_#{i}.pid"<br>
contents = File.read(fn)<br>
if contents.size > 1<br>
puts "file #{fn} was written to many times (#{contents})"<br>
borked = true<br>
end<br>
end<br>
exit(false) if borked<br>
end</p>
<p>As you can see from the comments inside the fork I can work around the<br>
issue by using "exit!". I am correct in understanding that there should be<br>
no case in which the file is written to multiple times, correct?</p>
<p>Thank you,<br>
Jason Gladish</p> Ruby master - Feature #8184 (Open): Avoid the creation of meaningless ranges (nil, false, true)https://bugs.ruby-lang.org/issues/81842013-03-29T23:16:36Zphi (Pascal Hurni)hurnip@gmail.com
<p>With the definition of <=> on Object on post 1.8, the range_init() function no more throws "ArgumentError: bad value for range" when creating these ranges:<br>
nil..nil<br>
false..false<br>
true..true</p>
<p>These kind of ranges are meaningless, the majority of methods on Range do not work on them, like (nil..nil).include?(nil).</p>
<p>This feature request (with patch) re-introduces the 1.8 behaviour of throwing ArgumentError when creating such ranges.</p> Ruby master - Feature #8088 (Open): Method#parameters (and friends) should provide useful informa...https://bugs.ruby-lang.org/issues/80882013-03-14T07:56:06Zheadius (Charles Nutter)headius@headius.com
<p>I was wiring up #parameters to work for native methods today when I realized MRI doesn't give very good information about variable-arity native methods:</p>
<pre><code>$ ruby2.0.0 -e "p ''.method(:gsub).to_proc.parameters"
[[:rest]]
$ jruby -e "p ''.method(:gsub).to_proc.parameters"
[[:req], [:opt]]
</code></pre>
<p>I think MRI should present the same as JRuby here; gsub is obviously not a rest-arg method and you can't call it with less than 1 or more than 2 arguments. JRuby's presenting the right output here.</p>
<p>I'm probably going to have to change JRuby to do the less-helpful version so we're compliant and tests pass, but I think the specification of #parameters should be that it presents the JRuby version about rather than the MRI version.</p> Ruby master - Feature #8061 (Open): 重複するキーワードをエラーにするhttps://bugs.ruby-lang.org/issues/80612013-03-10T09:53:22Ztadf (tadayoshi funaba)
<p>重複するキーワードをエラーにする。</p>
<p>def m(a:1, b:2)<br>
p [a, b]<br>
end</p>
<p>m(a:8, a:9)</p> Ruby master - Feature #8046 (Open): allow Object#extend to take a blockhttps://bugs.ruby-lang.org/issues/80462013-03-08T11:48:34Zphluid61 (Matthew Kerwin)matthew@kerwin.net.au
<p>=begin<br>
In <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Keyword `object` to be used instead of `class <<` (Rejected)" href="https://bugs.ruby-lang.org/issues/8038">#8038</a> david_macmahon proposed:</p>
<p>How about allowing Object#extend to take a block that would be executed with the context such that methods defined therein would become singleton methods of the object receiving #extend?</p>
<p>For example:<br>
foo = Object.new<br>
foo.extend do<br>
def bar<br>
# ...<br>
end<br>
def baz<br>
# ...<br>
end<br>
end<br>
=end</p> Ruby master - Feature #7981 (Open): ruby does not respect --https://bugs.ruby-lang.org/issues/79812013-02-28T08:40:08Zmpapis (Michal Papis)mpapis@gmail.com
<p>=begin<br>
in ((%ruby --help%)) I have found:</p>
<pre><code>Usage: ruby [switches] [--] [programfile] [arguments]
</code></pre>
<p>so I have tried this example:</p>
<pre><code>$ echo 'puts :ok' | ruby -- --params
> ruby: No such file or directory -- --params (LoadError)
</code></pre>
<p>I have assumed that ((%[argumments]%)) are independent from ((%[programfile]%))</p>
<p>In the current state of code the help message should be:</p>
<pre><code>Usage: ruby [switches] [--] [programfile [arguments]]
</code></pre>
<p>But I would prefer that it would be fixed and anything after ((%[--]%)) that is not program gets ignored, so we can use the shell style:</p>
<pre><code>$ echo 'echo "args:$*:"' | bash -s -- --params
> args:--params:
</code></pre>
<p>=end</p> Ruby master - Feature #7914 (Open): Case for local class methodshttps://bugs.ruby-lang.org/issues/79142013-02-23T00:13:20Ztrans (Thomas Sawyer)
<p>=begin<br>
Here is a use case for local class methods.</p>
<p>Say we wish to give certain classes and all subclasses a special name.</p>
<p>class X<br>
def self.special_name<br>
"special:#{name}"<br>
end<br>
end<br>
class Y < X; end<br>
class Z < Y; end</p>
<p>Z.special_name #=> "special:Z"</p>
<p>But what if Y has a unique special name?</p>
<p>class Y < X<br>
def special_name<br>
'unique:Y'<br>
end<br>
end</p>
<p>Problem that arises:</p>
<pre><code>Z.special_name #=> "unique:Y" # wrong!
</code></pre>
<p>Currently, to solve this would require creating an additional method, e.g. <code>unique_name</code> and redefine <code>special_name</code> to first look for unique_name then fallback to default special name if non-found. It works, but adds additional complexity to API.</p>
<p>Nicer solution would be local class methods.</p>
<pre><code>class Y < X
def special_name
'unique:Y'
end
local :special_name
end
Y.special_name #=> "unique:Y"
Z.special_name #=> "special:Z"
</code></pre>
<p>The idea being that local class methods are skipped in super/lookup chain.</p>
<p>This idea is not without precedence. Module class methods can be thought of as being local. So this idea has other side of the notion, that modules could have class methods that are not skipped over in the super/lookup chain. In that case we would need a term that means opposite of local, so I'll use <code>nonlocal</code>:</p>
<pre><code>module M
def self.q; "q"; end
nonlocal :q
end
class X
include M
end
X.q #=> "q"
</code></pre>
<p>=end</p> Ruby master - Feature #7895 (Open): Exception#backtrace_locations to go with Thread#backtrace_loc...https://bugs.ruby-lang.org/issues/78952013-02-21T06:02:25Zheadius (Charles Nutter)headius@headius.com
<p>Thread#backtrace_locations and Kernel#caller_locations were added in Ruby 2.0.0, but no equivalent method was added to Exception to get backtrace locations. The String format of Exception#backtrace elements makes it difficult to do any inspection of the actual files and lines it reports, so having backtrace_locations would be very useful.</p>
<p>In <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Exceptions should have backtrace_locations (Rejected)" href="https://bugs.ruby-lang.org/issues/7435">#7435</a> ko1 pointed out that Exception defines set_backtrace, which takes an array (presumably of Strings in the same format as Exception#backtrace) and that this would need to be addressed in order to support backtrace_locations. I propose that if you set_backtrace, you are already breaking the ability to get structured Location elements, so set_backtrace should cause backtrace_locations to return nil or an empty array (probably an empty array, so it can always be expected to be non-nil).</p>
<p>We could consider also adding set_backtrace_locations as a way to set Location elements into the exception.</p>
<p>An example script where backtrace_locations would be very useful is here (avoiding the need to regexp match to get file and line number): <a href="https://gist.github.com/headius/4999244" class="external">https://gist.github.com/headius/4999244</a></p> Ruby master - Bug #7892 (Open): MIME encoding bug of NKF.nkfhttps://bugs.ruby-lang.org/issues/78922013-02-20T16:01:52Zmrkn (Kenta Murata)muraken@gmail.com
<p>NKF の MIME encoding の結果が 1.8 と 1.9/2.0 で異なってます。</p>
<a name="18-の場合"></a>
<h1 >1.8 の場合<a href="#18-の場合" class="wiki-anchor">¶</a></h1>
<p>$ /usr/bin/ruby -rnkf -ve "puts NKF.nkf('-jW -M --cp932', '「あああああああああああ by ああああああああああ」のレシピ')"<br>
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin11.0]<br>
=?ISO-2022-JP?B?GyRCIVYkIiQiJCIkIiQiJCIkIiQiJCIkIiQiGyhC?= by<br>
=?ISO-2022-JP?B?GyRCJCIkIiQiJCIkIiQiJCIkIiQiJCIhVyROJWwlNyVUGyhC?=</p>
<a name="193-p385-の場合"></a>
<h1 >1.9.3-p385 の場合<a href="#193-p385-の場合" class="wiki-anchor">¶</a></h1>
<p>$ ruby -rnkf -ve "puts NKF.nkf('-jW -M --cp932', '「あああああああああああ by ああああああああああ」のレシピ')"<br>
ruby 1.9.3p385 (2013-02-06 revision 39114) [x86_64-darwin11.4.2]<br>
=?ISO-2022-JP?B?GyRCIVYkIiQiJCIkIiQiJCIkIiQiJCIkIiQiGyhC?= by<br>
=?US-ASCII?Q??=<br>
=?ISO-2022-JP?B?GyRCJCIkIiQiJCIkIiQiJCIkIiQiJCIhVyROJWwlNyVUGyhC?=</p>
<a name="200-rc2-の場合"></a>
<h1 >2.0.0-rc2 の場合<a href="#200-rc2-の場合" class="wiki-anchor">¶</a></h1>
<p>$ RBENV_VERSION=2.0.0-rc2 rbenv exec ruby -rnkf -ve "puts NKF.nkf('-jW -M --cp932', '「あああああああああああ by ああああああああああ」のレシピ')"<br>
ruby 2.0.0dev (2013-02-08 trunk 39161) [x86_64-darwin11.4.2]<br>
=?ISO-2022-JP?B?GyRCIVYkIiQiJCIkIiQiJCIkIiQiJCIkIiQiGyhC?= by<br>
=?US-ASCII?Q??=<br>
=?ISO-2022-JP?B?GyRCJCIkIiQiJCIkIiQiJCIkIiQiJCIhVyROJWwlNyVUGyhC?=</p> Ruby master - Feature #7883 (Open): Add Regex#to_prochttps://bugs.ruby-lang.org/issues/78832013-02-19T16:58:30Zrklemme (Robert Klemme)shortcutter@googlemail.com
<p>Just a small addition to the standard library:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">class</span> <span class="nc">Regexp</span>
<span class="k">def</span> <span class="nf">to_proc</span><span class="p">;</span> <span class="nb">lambda</span> <span class="p">{</span><span class="o">|</span><span class="n">s</span><span class="o">|</span> <span class="nb">self</span> <span class="o">=~</span> <span class="n">s</span><span class="p">}</span> <span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>With that one can use a <code>Regexp</code> everywhere a <code>Proc</code> is used as filtering criteria saving a bit of typing. While we have <code>Enumerable#grep</code> already there may be other cases where you want to do something like</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">irb</span><span class="p">(</span><span class="n">main</span><span class="p">):</span><span class="mo">00</span><span class="mi">8</span><span class="p">:</span><span class="mi">0</span><span class="o">></span> <span class="sx">%w{foo bar baz}</span><span class="p">.</span><span class="nf">select</span> <span class="o">&</span><span class="sr">/\Ab/</span>
<span class="o">=></span> <span class="p">[</span><span class="s2">"bar"</span><span class="p">,</span> <span class="s2">"baz"</span><span class="p">]</span>
<span class="n">irb</span><span class="p">(</span><span class="n">main</span><span class="p">):</span><span class="mo">00</span><span class="mi">9</span><span class="p">:</span><span class="mi">0</span><span class="o">></span> <span class="sx">%w{foo bar baz}</span><span class="p">.</span><span class="nf">reject</span> <span class="o">&</span><span class="sr">/\Ab/</span>
<span class="o">=></span> <span class="p">[</span><span class="s2">"foo"</span><span class="p">]</span>
<span class="n">irb</span><span class="p">(</span><span class="n">main</span><span class="p">):</span><span class="mo">010</span><span class="p">:</span><span class="mi">0</span><span class="o">></span> <span class="sx">%w{foo bar baz}</span><span class="p">.</span><span class="nf">find</span> <span class="o">&</span><span class="sr">/\Ab/</span>
<span class="o">=></span> <span class="s2">"bar"</span>
</code></pre>
<p>Note: line 9 and 10 are not possible with <code>Enumerable#grep</code> AFAIK.</p>
<p>I see low risk of breaking something.</p> Ruby master - Feature #7876 (Open): Add method for accessing Class from within Singleton Classhttps://bugs.ruby-lang.org/issues/78762013-02-18T19:59:29Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
I'm quite surprised I haven't run into this sooner, but I seem to have just discovered that there's no means by which you can access the outer Class object once inside the context of the Singleton Class. Take the following example; how would I get a reference to (({Test})) from within the singleton?</p>
<p>class Test<br>
class << self<br>
# How do I get a reference to Test from here?<br>
end<br>
end</p>
<p>I assume the answer is that there is no reliable way, hence the reason for this request. Could we add a method to the singleton class that allows access to the "outer" class, e.g.</p>
<p>class Test<br>
class << self<br>
self.outerclass<br>
end<br>
end</p>
<p>Thoughts?<br>
=end</p> Ruby master - Feature #7848 (Open): Restore default state for core ruby objectshttps://bugs.ruby-lang.org/issues/78482013-02-14T04:41:33Zshevegen (Robert A. Heiler)shevegen@gmail.com
<p>Hi.</p>
<p>Consider:</p>
<p>class String<br>
def lala<br>
puts 'Running lala() from class String.'<br>
end<br>
end</p>
<p>This is possible.</p>
<p>My question is - is there a reason why we can not restore<br>
to the default ruby state again?</p>
<p>For instance, if I would do:</p>
<p>String.restore</p>
<p>I could undo all modifications to String, save what was used<br>
in String class on startup/initialize.</p>
<p>The reason I would like to have something like this is so<br>
that I could safely undo all "monkey" patches again, if needed,<br>
for a given project.</p> Ruby master - Feature #7845 (Open): Strip doesn't handle unicode space characters in ruby 1.9.2 &...https://bugs.ruby-lang.org/issues/78452013-02-14T00:27:55Ztimothyg56 (Timothy Garnett)timothyg@alum.mit.edu
<p>Strip and associated methods in ruby 1.9.2 and 1.9.3 do not remove leading/trailing unicode space characters (such as non-breaking space \u00A0 and ideographic space \u3000) unlike ruby 1.9.1. I'd expect the 1.9.1 behavior. Looking at the underlying native lstrip! and rstrip! methods it looks like this is because 1.9.1 uses rb_enc_isspace() whereas 1.9.2+ uses rb_isspace().</p>
<p>1.9.1p378 :001 > "\u3000\u00a0".strip<br>
=> ""</p>
<p>1.9.2p320 :001 > "\u3000\u00a0".strip<br>
=> " "</p>
<p>1.9.3p286 :001 > "\u3000\u00a0".strip<br>
=> " "</p> Ruby master - Feature #7795 (Open): Symbol.defined? and/or to_existing_symbolhttps://bugs.ruby-lang.org/issues/77952013-02-07T14:08:11ZStudent (Nathan Zook)blogger@pierian-spring.net
<p>I'm pulling this out from deep in the discussions of issue <a href="http://bugs.ruby-lang.org/issues/7791" class="external">http://bugs.ruby-lang.org/issues/7791</a>, Let Symbols be Garbage Collected.</p>
<p>The problem is that the extreme utility of symbols makes them enticed to use, which results in a DOS vulnerability. My proposal is to add either of a pair of methods that would make it easy to defend against a DOS along these lines.</p>
<p>#1) Symbol.defined?</p>
<p>In existing code, it would might like this:<br>
class Symbol<br>
def self.defined?(string)<br>
all_symbols.any?{|sym| sym.to_s == string}<br>
end<br>
end</p>
<p>#2) to_existing_sym. This would be defined in the same places as to_sym, but would through an argument error if the symbol did not already exist.</p> Ruby master - Feature #7788 (Open): YAML Tag Schema Supporthttps://bugs.ruby-lang.org/issues/77882013-02-06T05:05:55Ztrans (Thomas Sawyer)
<p>=begin<br>
I have endeavoured to add proper Schema support to Psych (see ((<YAML Spec|URL:<a href="http://www.yaml.org/spec/1.2/spec.html#Schema%3E" class="external">http://www.yaml.org/spec/1.2/spec.html#Schema></a>)) on Schemas). The primary reasons for supporting schemas are two fold: security and global tag conflict. The first is well known b/c of recent events. The second is less realized, but consider is it same problem as using global variables. Different apps have different tags; two identical local tags may have different meanings and thus cause conflict.</p>
<p>The API works like this:</p>
<pre><code>class Foo
end
foo_schema = YAML::Schema.new do |s|
s.tag '!foo', Foo
end
YAML.load('foo.yml', :schema=>foo_schema)
</code></pre>
<p>This code would allow only failsafe and json schema tags (core defaults), plus the specifically defined !foo tag.<br>
Also, %TAG prefix is supported:</p>
<pre><code>foo_schema = YAML::Schema.new(:prefix=>{'!'=>'tag:foo.org/'}) do |s|
s.tag '!foo', Foo
end
</code></pre>
<p>This will add tag 'tag:foo.org/foo<code>instead of local</code>!foo` tag.</p>
<p>To properly support schema, object's must store the tag with which they were loaded in order to ensure correct round tripping. For this there is <code>tag_uri</code> attribute.<br>
(Note: I am not sure if it best to store as instance variable, which it currently is, or to store in global table. Need feedback.)</p>
<p>In the process of adding schema support I was able to clean up and generalize loading code. For immutable types and class factories, adding (({ClassName.new_with(coder)})) can be used to instantiate class.</p>
<p>Implementation is close to complete, I believe this is all that remains:</p>
<ol>
<li>ScalarScanner needs to respect schema (basically if failsafe and/or json schemas are not used).</li>
<li>Dumping needs to take :schema option to limit it to schema tags.</li>
<li>Dumping needs to look to tag_uri for tag by default.</li>
<li>There is one bug I have yet to figure out (test_spec_builtin_map).</li>
<li>I have questions about Coder, b/c it seems more complex than it needs to be.</li>
</ol>
<p>I am also considering refactoring Schemas as modules that can be included into other schema. Currently they are classes/objects that can be subclassed or merged via <code>+</code>, e.g.</p>
<pre><code>LEGACY_SCHEMA = CORE_SCHEMA + RUBY_SCHEMA + OBJECT_SCHEMA + SYCK_SCHEMA
</code></pre>
<p>Of course, as with any new code, there's sure to be corner cases to work out. Having other pound on it for a while would be very helpful. Oh, and I should also mention I am documenting as much of the code as can.</p>
<p>Feel free to ask me any questions for more details about the code. You can find the branch here: <a href="https://github.com/trans/psych/tree/isotag" class="external">https://github.com/trans/psych/tree/isotag</a><br>
=end</p> Ruby master - Feature #7748 (Open): Contextual sendhttps://bugs.ruby-lang.org/issues/77482013-01-28T16:11:40Ztrans (Thomas Sawyer)
<p>=begin<br>
If I write a method that uses #send vs. #public_send, I am making an assumption about how that method is invoked. For example, take the simplest form of such a method:</p>
<p>class String<br>
def send_out(op, *a, &b)<br>
send(op, *a, &b)<br>
end<br>
end</p>
<p>This code has a bug in it, in the sense that it can be used to call private string methods. The solution is to use #public_send. In most cases that will be fine. But if anyone tries to reuse the method while extending String themselves, e.g.</p>
<p>class String<br>
def send_out(op, *a, &b)<br>
public_send(op, *a, &b)<br>
end</p>
<pre><code>def some_public_method
send_out(:some_private_method)
end
private
def some_private_method
end
</code></pre>
<p>end</p>
<p>Then it will be a problem b/c it cannot be used on a private supporting method.</p>
<p>So it seems like there should be something like a ((<em>contextual send</em>)) which invokes a send with the same visibility as the parent method is invoked. e.g.</p>
<p>class String<br>
def send_out(op, *a, &b)<br>
contextual_send(op, *a, &b)<br>
end<br>
end</p>
<p>And then all cases will work as expected.<br>
=end</p> Ruby master - Feature #7747 (Open): Expanded API for Binding semanticshttps://bugs.ruby-lang.org/issues/77472013-01-28T08:08:12Zjballanc (Joshua Ballanco)jballanc@gmail.com
<p>=begin<br>
Currently, the only way to create a new instance of Binding is to get a copy of the current scope's binding, or ask some other object for its binding. In either case, the binding object returned always has semantics identical to the original binding. In other words, a binding object used with eval is capable of (not necessarily an exhaustive list):</p>
<ul>
<li>redefining methods on the binding target</li>
<li>defining new methods on the binding target</li>
<li>getting/setting instance variables</li>
<li>getting/creating new constants</li>
</ul>
<p>This feature proposal would introduce a new mechanism for creating a binding and adjusting its relationship with the source binding. For example, if you have a class (({Foo})) defined like so:</p>
<pre><code>class Foo
def say
puts "hello!"
end
end
</code></pre>
<p>Then you would be able to create a new binding that ((<em>won't</em>)) propagate new definitions to the parent binding like so:</p>
<pre><code>new_binding = Binding.new(Foo)
new_binding.propagate = false
new_binding.eval("def shout; puts 'HI!'; end")
Foo.new.say #=> "hello!"
Foo.new.shout #=> No Method Error
new_binding.eval("Foo.new.say") #=> "hello"
new_binding.eval("Foo.new.shout") #=> "HI!"
</code></pre>
<p>If, additionally, we introduce a way to merge or combine bindings, then this API could actually be used to implement refinements in pure Ruby like so (note I am also assuming that (({Binding#eval})) gains the ability to take a block):</p>
<pre><code>class Module
def refine(klass, &block)
@refined_bindings ||= {}
refinement_binding = Binding.new(klass)
refinement_binding.propagate = false
refinement_binding.shadow = true
refinement_binding.eval &block
(@refined_bindings[self.name] ||= []) << refinement_binding
end
def using(mod)
@refined_bindings[mod].each { |refinement| self.binding.merge(refinement) }
end
end
</code></pre>
<p>Following is the preliminary list of additional APIs I am tentatively proposing (though I expect this to change with additional discussion):</p>
<ul>
<li>(({Binding.new(an_object)})) - creates a new Binding object that "inherits" the binding of the argument; essentially equivalent to (({an_object.send(:binding).dup}))</li>
<li>(({Binding#propagate}))/(({Binding#propagate=})) - boolean; determines whether new method, class, or Constant defs are propagated into the "parent" binding's scope</li>
<li>(({Binding#shadow}))/(({Binding#shadow=})) - boolean; sets whether or not new values for existing methods/constants/variables can be set</li>
<li>(({Binding#freeze})) - causes the Binding to capture all existing methods/constants/variables in scope at call time, and "disconnect" from the parent binding, so that any updates to definitions or values are no longer reflected into the "child" binding</li>
<li>(({Binding#merge(other_binding)})) - combines the method/constant/variable bindings in (({other_binding})) with the receiver; effectively shadows the "parent" of (({other_binding})) within the receiver binding<br>
=end</li>
</ul> Ruby master - Feature #7745 (Open): lib/observer.rb: Observers are compared by identityhttps://bugs.ruby-lang.org/issues/77452013-01-28T02:19:15Zzzak (zzak _)
<p>=begin<br>
From ((<github issue 239|URL:<a href="https://github.com/ruby/ruby/pull/239%3E" class="external">https://github.com/ruby/ruby/pull/239></a>)):</p>
<p>((<em>Please consider changing @observer_peers to compare_by_identity. This fixes surprising effects when Strings or Arrays are used as observers.</em>))</p>
<p>I've attached the associated patch.<br>
=end</p> Ruby master - Bug #7742 (Open): System encoding (Windows-1258) is not recognized by Ruby to conv...https://bugs.ruby-lang.org/issues/77422013-01-26T15:33:40ZMars (Hong Ha Dang )dhhmars9999@gmail.com
<p>I installed Railsinstaller in win8. After intall complete the screen set to</p>
<blockquote>
<p>configuration Railsinstaller on cmd (step 2). I give user name: DHH Mars and<br>
email: <a href="mailto:dhhma...@gmail.com" class="email">dhhma...@gmail.com</a>. It ran and have following massage:</p>
<p>C:/RailsInstaller/scripts/config_check.rb:64:in 'exist?': code converter not<br>
found <a href="Encoding::ConverterNotFoundError" class="external">Encoding::ConverterNotFoundError</a> from<br>
C:/RailsInstaller/scripts/config_check.rb:64:in 'main'</p>
<p>C:\Sites></p>
</blockquote> Ruby master - Feature #7708 (Open): support for patches listhttps://bugs.ruby-lang.org/issues/77082013-01-17T04:39:42Zmpapis (Michal Papis)mpapis@gmail.com
<p>Often as maintainer of RVM I have to work with multiple ruby patches, but it's hard to tell what patches were used for compiling ruby. As a temporary solution I have started using a file <code>patches.list</code> in the root of source and installation directory. It would be nice if Ruby would include this list also in RbConfig::CONFIG.</p>
<p>Here is example content of the file I have for ruby-1.9.3-p362:</p>
<pre><code>ruby-multilib
segfault_fix_7629
</code></pre>
<p>If that would be implemented I could understand if it would be required the files to be URLs to online patches which can be easily downloaded and analyzed.</p> Ruby master - Feature #7704 (Open): Add a list of enabled (experimental) language features.https://bugs.ruby-lang.org/issues/77042013-01-16T10:54:37Zmpapis (Michal Papis)mpapis@gmail.com
<p>With multiple Ruby implementations and "experimental" features like "refinements" it would be nice to have an array or hash including list of enabled language features so developers could check it instead of auto-discovering code with some hacks.</p>
<p>Additionally a new keyword like <code>require_features :refinements, ...</code> could be introduced to allow easy validation via either exception or return status.</p> Ruby master - Feature #7702 (Open): Remove Proc#bindinghttps://bugs.ruby-lang.org/issues/77022013-01-16T09:09:14Zjballanc (Joshua Ballanco)jballanc@gmail.com
<p>=begin<br>
As discussed in the most recent Ruby implementer's meeting and elsewhere over the years, being able to get a handle to the binding of any block/proc has a number of problems:</p>
<ul>
<li>Code execution after passing a block/proc in unpredictable, as the binding of said proc can be used to redefine any local, instance variable, method, class, module, etc.</li>
<li>Potentially sensitive data can leak out of the scope of a method via a proc binding</li>
<li>Large object graphs may need to be retained for the lifetime of a proc, since any identifier in scope at the time of proc creation must remain live in the event that the binding of the proc is used to evaluate code</li>
</ul>
<p>Additionally, removal of Proc#binding would enable a number of very useful optimizations and performance improvements.<br>
=end</p> Ruby master - Feature #7657 (Open): Array#& doesn't accept Enumerableshttps://bugs.ruby-lang.org/issues/76572013-01-06T09:00:39ZNevir (Ian MacLeod)ian@nevir.net
<p>This seems similar to <a href="http://bugs.ruby-lang.org/issues/6923" class="external">http://bugs.ruby-lang.org/issues/6923</a></p>
<p>Example:</p>
<pre><code>irb(main):001:0> class Thing
irb(main):002:1> include Enumerable
irb(main):003:1> def each(*args, &block)
irb(main):004:2> [1,2,3,4,5].each(*args, &block)
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Array(Thing.new) & [1,3,5]
=> [1, 3, 5]
irb(main):008:0> [1,3,5] & Thing.new
TypeError: can't convert Thing into Array
irb(main):009:0> Thing.class_eval do
irb(main):010:1* alias_method :to_ary, :to_a
irb(main):011:1> end
=> Thing
irb(main):012:0> [1,3,5] & Thing.new
=> [1, 3, 5]
</code></pre>
<p>Would it make sense for Enumerable to implement to_ary as well? Or is this purely a bug in Array#&?</p> Ruby master - Feature #7654 (Open): Add optional code block to IO::readlineshttps://bugs.ruby-lang.org/issues/76542013-01-04T22:15:05Zshock_one (Володимир Шацький)shockone89@gmail.com
<p>Of course, we always can write something like<br>
File.readlines('/home/shock_one/test.rb').map{ |line| line.upcase }<br>
but this way we create unneeded intermediate array which can be pretty big.<br>
There is also a method IO::foreach, but it doesn't collect return values.<br>
Besides it seems pretty logical and natural to have a block in this method.</p> Ruby master - Feature #7614 (Open): alias_accessorhttps://bugs.ruby-lang.org/issues/76142012-12-24T11:19:06Ztrans (Thomas Sawyer)
<p>=begin<br>
Prior issue reminded me that I've been meaning to ask for this for a while, as I use is fairly often.</p>
<p>In pure Ruby the definition is essentially:</p>
<pre><code>def alias_accessor(name, origin)
alias_method "#{name}=", "#{origin}="
alias_method name, origin
end
</code></pre>
<p>Albeit pursuit to prior mentioned issue, I'd define it more like:</p>
<pre><code>def alias_accessor(name, origin)
writer_name = name.to_s.chomp('?')
alias_method "#{writer_name}=", "#{origin}="
alias_method name, origin
end
</code></pre>
<p>=end</p> Ruby master - Feature #7611 (Open): Focal method for all loads/requireshttps://bugs.ruby-lang.org/issues/76112012-12-23T23:50:40Ztrans (Thomas Sawyer)
<p>=begin<br>
Presently Ruby has seven methods for importing code. These are:</p>
<ul>
<li>(({Kernel#load}))</li>
<li>(({Kernel#require}))</li>
<li>(({Kernel#relative_require}))</li>
<li>(({Kernel.load}))</li>
<li>(({Kernel.require}))</li>
<li>(({Kernel.relative_require}))</li>
<li>(({Kernel#autoload}))</li>
</ul>
<p>Even though the Kernel module methods do the same thing as the instance methods, all of these act independently. If you need to tap into or override code loading in general it means doing so for each and every one.</p>
<p>Would it not be much more elegant if they all called upon one focal method? Lacking another name for this example, lets call it (({#open_eval()})). The method would take a path argument and options for (({feature})), (({relative})) and (({wrap})), where if (({feature})) is true then it is a "require", otherwise it is a "load".</p>
<p>def open_eval(path, feature: false, relative: false, wrap: nil)<br>
...<br>
end</p>
<p>All the other seven methods listed above would route to this one method. So it would then be possible to monitor or override this behavior, e.g. like RubyGems does, via a single interface.</p>
<p>Note, even if this feature request is not accepted, I would like to get some opinion on it, b/c I am currently working on a project where I have to do this (specifically I am in need of require/load callbacks). For the purpose I have created another reusable gem for it and I want to get an idea of what would be considered appropriate API for it.<br>
=end</p> Ruby master - Feature #7604 (Open): Make === comparison operator ability to delegate comparison t...https://bugs.ruby-lang.org/issues/76042012-12-22T21:04:06Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>=begin<br>
I propose to expand default behaviour of === operator in the following way:<br>
Objects have additional instance method Object#reverse_comparison?(other) which is false by default in all basic classes.<br>
Each class that overrides Object#===(other) should check whether reverse_comparison? is true or false<br>
If it is false, behavior is not changed at all.<br>
If it is true, comparison is delegated to === method of an argument with self as an argument.</p>
<p>This technique can help in constructing RSpec-style matchers for case statement. Example:</p>
<a name="usual-method-call"></a>
<h1 >usual method call<a href="#usual-method-call" class="wiki-anchor">¶</a></h1>
<p>arr = %w[cat dog rat bat]<br>
puts arr.end_with?(%w[dog bat]) # ==> false<br>
puts arr.end_with?(%w[rat bat]) # ==> true<br>
puts arr.end_with?(%w[bat]) # ==> true</p>
<a name="predicate-style-case"></a>
<h1 >predicate-style case<a href="#predicate-style-case" class="wiki-anchor">¶</a></h1>
<p>case %w[cat dog rat bat].end_with?<br>
when %w[dog bat]<br>
puts '..., dog, bat'<br>
when %w[rat bat]<br>
puts '..., rat, bat'<br>
when %w[bat]<br>
puts '..., bat'<br>
else<br>
puts 'smth else'<br>
end</p>
<a name="gt-rat-bat"></a>
<h1 >==> ..., rat, bat<a href="#gt-rat-bat" class="wiki-anchor">¶</a></h1>
<p>Code needed to run this is not very complex:<br>
class Object<br>
def reverse_comparison?(other)<br>
false<br>
end<br>
alias_method :'old===', :'==='<br>
def ===(other)<br>
(other.reverse_comparison?(self) ? (other.send 'old===',self) : (self.send 'old===',other))<br>
end<br>
end</p>
<p>class Predicate<br>
def initialize(&block)<br>
@block = block<br>
end<br>
def reverse_comparison?(other)<br>
true<br>
end<br>
def ===(*args)<br>
@block.call(*args)<br>
end<br>
end</p>
<p>class Array<br>
alias_method :'old===', :'==='<br>
def ===(other)<br>
other.reverse_comparison?(self) ? (other.send('===',self)) : (self.send('old===',other))<br>
end</p>
<pre><code>def end_with?(expected_elements = nil)
return last(expected_elements.size) == expected_elements if expected_elements
Predicate.new{|suffix| last(suffix.size) == suffix }
end
</code></pre>
<p>end</p>
<p>This technique looks powerful and beautiful for me. One detail is that obj#reverse_comparison? can distinguish different types of arguments and returns true only for certain types of given object. Also this can be used to prevent double-mirroring (as shown below)</p>
<p>The problem is that many base classes already defined custom === operator, so each of those classes (Fixnum, Float, String, Regexp, Range etc) should be redefined in such a way to make a solution full-fledged.<br>
Another problem is case that both objects defined reverse_comparison? to return true. In my solution Predicate#=== just ignores result of revese_comparison? which is not consistent.<br>
Another possible way is to raise errors on double mirroring:<br>
def reverse_comparison?(other)<br>
raise 'double mirroring' if @__mirroring_started<br>
@__mirroring_started = true<br>
return true unless other.reverse_comparison?(self)<br>
false<br>
ensure<br>
remove_instance_variable :@__mirroring_started<br>
end</p>
<p>My proposal is to add reverse_comparison? method and change base classes operator === to use its result as shown above. May be it's worth also to make a class analogous to Predicate in stdlib.<br>
=end</p> Ruby master - Feature #7548 (Open): Load and Require Callbackshttps://bugs.ruby-lang.org/issues/75482012-12-12T13:15:48Ztrans (Thomas Sawyer)
<p>=begin<br>
Should #load and #require have callbacks? e.g.</p>
<p>def required(path)<br>
...<br>
end</p>
<p>def loaded(path, wrap)<br>
...<br>
end</p>
<p>On occasion I have wanted to do load monitoring to track down a bug. This would have made it easier.</p>
<p>Are there any other good use cases?<br>
=end</p> Ruby master - Feature #7546 (Open): Change behavior of `Array#slice` for an argument of `Range` c...https://bugs.ruby-lang.org/issues/75462012-12-12T01:23:22Zalexeymuranov (Alexey Muranov)
<p>=begin<br>
This is a concrete proposal to "fix" <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Inconsistent Array.slice() (Rejected)" href="https://bugs.ruby-lang.org/issues/4541">#4541</a>.</p>
<p>It is also related to <a class="issue tracker-2 status-1 priority-4 priority-default" title="Feature: Make Range act as a "lazy ordered set" (Open)" href="https://bugs.ruby-lang.org/issues/7545">#7545</a>.<br>
For this proposal to make good sense, i think it would be nice if <a class="issue tracker-2 status-1 priority-4 priority-default" title="Feature: Make Range act as a "lazy ordered set" (Open)" href="https://bugs.ruby-lang.org/issues/7545">#7545</a> was at least partially accepted.</p>
<p>=== Main proposal</p>
<p>I propose (({Array#slice})) with (({Range})) type argument to work as follows:</p>
<p>a = ['0', '1', '2', '3']<br>
a[1..2] # => ['1', '2']<br>
a[-2..-1] # => ['2', '3']<br>
a[2..1] # => ['2', '1']<br>
a[-1..-2] # => ['3', '2']<br>
a[-1..1] # => ['3', '0', '1']<br>
a[1..-1] # => ['1', '0', '3']<br>
a[1..1] # => ['1']<br>
a[1...1] # => []<br>
a[4..4] # => [nil]<br>
a[4...4] # => []<br>
a[9..9] # => [nil]<br>
a[9...9] # => []<br>
a[1..5] # => ['1', '2', '3', nil, nil]</p>
<p>=== Secondary proposal: consider adding new instance methods to (({Array})) to compensate the changed behavior of (({Array#slice}))</p>
<p>If this proposal is accepted, the code "(({a[1..-2]}))" for an array (({a})) will not work as before.<br>
This can be compensated by adding new instance methods to (({Array})).<br>
For example the following ones.</p>
<ol>
<li>(({Array#clip(fixnum, fixnum)})):</li>
</ol>
<p>['0', '1', '2', '3'].clip(1, 1) # => ['1', '2']</p>
<p>Thus (({a.clip(1, 1)})) would be a replacement for (({a[1..-2]})).</p>
<p>(It looks strange to have to convert a pair of numbers ((<em>m</em>)) and ((<em>n</em>)) into a range (({m..(-1-n)})) to simply ask an array to remove ((<em>m</em>)) elements from the beginning and ((<em>n</em>)) elements from the end.<br>
If <a class="issue tracker-2 status-1 priority-4 priority-default" title="Feature: Make Range act as a "lazy ordered set" (Open)" href="https://bugs.ruby-lang.org/issues/7545">#7545</a> is accepted, then the "(({a[1..-2]}))" syntax for "clipping" an array will make not much sense and maybe will not be possible.)</p>
<ol start="2">
<li>(({Array#from(fixnum)})), (({Array#till(fixnum)})):</li>
</ol>
<p>a = ['0', '1', '2', '3']<br>
a.from(1) # => ['1', '2', '3']<br>
a.till(1) # => ['0', '1']<br>
a.from(1).till(-2) # => ['1', '2']</p>
<p>In fact, in ((<em>Rails</em>)) (({ActiveSupport})) there are methods (({Array#from})) and (({Array#to})) like this, but unfortunately they do not accept negative indices.</p>
<p>((<em>Remark</em>)). It would also be possible to have (({Array#clip!})), (({Array#from!})), (({Array#till!})).<br>
=end</p> Ruby master - Feature #7545 (Open): Make Range act as a "lazy ordered set"https://bugs.ruby-lang.org/issues/75452012-12-12T01:05:47Zalexeymuranov (Alexey Muranov)
<p>=begin</p>
<a name="Make-Range-act-as-a-lazy-ordered-set"></a>
<h1 >Make Range act as a "lazy ordered set"<a href="#Make-Range-act-as-a-lazy-ordered-set" class="wiki-anchor">¶</a></h1>
<p>This replaces my older feature request <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Redefine Range class and introduce RelativeNumeric and RelativeRange (Rejected)" href="https://bugs.ruby-lang.org/issues/5534">#5534</a>.</p>
<p>I propose the following new behavior of (({Range})):</p>
<p>(1..3).to_a # => [1, 2, 3]<br>
(3..1).to_a # => [3, 2, 1]<br>
'a'..'c'.to_a # => ['a', 'b', 'c']<br>
'c'..'a'.to_a # => ['c', 'b', 'a']<br>
1...1 == 3...3 # => true<br>
1...1 == 'a'...'a' # => true<br>
1...1 == Range::EMPTY_SET # => true<br>
1..2 == 1...3 # => false<br>
1...3.include?(2.5) # => true</p>
<p>Also, maybe in the future the following behavior can be possible:</p>
<p>r1 = Range.new('a', 'bc', :deglex)<br>
r1.include?('abc') # => false<br>
r1.to_a # => ['a', 'b', ..., 'az', 'ba', 'bb', 'bc']<br>
r2 = Range.new('a', 'bc', :lex)<br>
r2.include?('abc') # => true<br>
r2.to_a # => Error</p>
<p>and this:</p>
<p>((0.5)..(5.5)).to_a(Integer) # => [1, 2, 3, 4, 5]<br>
((0.5)..(5.5)).each(Integer) do |i| puts i end</p>
<p>(i imagine this would require additions to the (({Integer})) class, so that it<br>
know more about "real" ranges).</p>
<p>=end</p> Ruby master - Feature #7444 (Open): Array#product_sethttps://bugs.ruby-lang.org/issues/74442012-11-27T14:44:28Zmarcandre (Marc-Andre Lafortune)marcandre-ruby-core@marc-andre.ca
<p>I'd like to propose <code>Array#product_set</code> to return the product set of arrays (aka cartesian product)</p>
<pre><code>deck = [1..13, %i(spades hearts diamond clubs)].product_set
# => <#Enumerator ...>
deck.first(2) # => [[1, :spades], [2, :spades]]
</code></pre>
<p><code>product_set</code> would return an enumerator if no block is given. It should raise an error if an element of the array is not an Enumerable, like Array#transpose or #zip do.</p>
<p>Although <code>Array.product</code> would be acceptable too, I feel that an instance method of array is best in the case, in the same way that <code>transpose</code> is an instance method and not a class method.</p>
<p>The name "product_set" is a correct mathematical term. Although the synonym "cartesian_product" would also be acceptable, I propose "product_set" because it is shorter and cute too. I feel it is even clearer than <code>product</code>; the first time I head of <code>product</code> I was convinced that <code>[2,3,7].product # => 42</code>.</p>
<p>Addressing objections raised in <a class="issue tracker-2 status-6 priority-4 priority-default closed" title="Feature: Array::zip (Rejected)" href="https://bugs.ruby-lang.org/issues/6499">#6499</a>:</p>
<ol>
<li>This is not for the sake of symmetry, but because often we have an array of the arrays we want a product of.</li>
</ol>
<p>It is cumbersome to write <code>arrays.first.product(*arrays[1..-1])</code> or similar and it hides what is going on.</p>
<p>Writing <code>arrays.product_set</code> is much nicer.</p>
<ol start="2">
<li>
<p>The goal is not mainly to get a lazy version, but more to make the API better. The fact that it returns an Enumerator if no block is given is just a bonus :-)</p>
</li>
<li>
<p>[].product_set.to_a # => [[]]</p>
</li>
</ol>
<p>This can be seen from a cardinality argument, or for example because <code>array.repeated_permutation(n) == Array.new(n, array).product_set.to_a</code> and <code>array.repeated_permutation(0) == [[]]</code>.</p> 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 #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 #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 #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 #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 #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 #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 #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 #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 #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 #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 #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>