Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112019-07-08T09:18:43ZRuby Issue Tracking System
Redmine Ruby master - Feature #15991 (Open): Allow questionmarks in variable nameshttps://bugs.ruby-lang.org/issues/159912019-07-08T09:18:43Zaquaj (Jérémie Bonal)
<p>Hi,</p>
<p>I thought such an issue would've already been discussed but no number of searches allowed me to find a similar request. Feel free to close if I missed a previous refusal.</p>
<p>From time to time, especially when trying to clear up complex conditional logic, I find myself wishing I could add <code>?</code> to variable names, since I got used to it while naming methods.</p>
<p>For example, currently:</p>
<pre><code>if (node? && terminal?) || (halting && (value == halting))
# ...
end
</code></pre>
<p>becomes</p>
<pre><code>last_node = self.node? && self.terminal?
halt_on_node = halting && (value == halting)
if last_node || halt_on_node
# ...
end
</code></pre>
<p><code>halt_on_node</code> is clear enough, but <code>last_node</code> feels like it would contain a node, instead of expressing its actual purpose ("is the node the last one?").<br>
Right now a developer would have two options as I see them:<br>
1 - extract the conditional to a method <code>def last_node?</code> which can be a bit much if it's the only place this code is called.<br>
2 - rename the variable something like <code>is_last_node</code>, which feels a bit silly since we're in ruby and used to seeing <code>?</code>s for predicates.</p>
<p>Trying to assign to a questionmarked variable (<code>a? = true</code>) raises a <code>SyntaxError</code>. IMHO, it would make for more coherent design to allow it, just like we do in method names.</p>
<p>I was afraid that <code>variable?</code> would be already parsed as beginning a ternary expression (<code>variable?1:3</code>) but this isn't parsed either, the only thing it's used for is for method calls (<code>a?5 <==> a?(5)</code>), so this change wouldn't disrupt any current behavior, the expression would just be looked up like any other call instead of only looking up methods.</p>
<p>The only thing I can see with this is that it might raise the issue of allowing <code>!</code>s in variable names too, which I'm not sure makes a lot of sense (unlike <code>?</code> which denotes "booleanness", a trait shared by variables and methods alike, I can't see how a variable would be "dangerous").</p> Ruby master - Feature #15837 (Open): Module#name_componentshttps://bugs.ruby-lang.org/issues/158372019-05-08T03:49:38Zmrkn (Kenta Murata)muraken@gmail.com
<p>I sometimes wrote the expression like below to extract the components of class path:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">klass</span><span class="p">.</span><span class="nf">name</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="s1">'::'</span><span class="p">).</span><span class="nf">last</span>
</code></pre>
<p>Similar expressions can be found in ruby-trunk:</p>
<pre><code>mrkn@mrkn-devel:~/src/github.com/ruby/ruby$ git grep split..::
ext/json/lib/json/common.rb: path.to_s.split(/::/).inject(Object) do |p, c|
ext/openssl/lib/openssl/config.rb: refsec, ref = ref.split('::', 2)
ext/psych/lib/psych/visitors/yaml_tree.rb: method = "visit_#{(klass.name || '').split('::').join('_')}"
lib/bundler/cli/gem.rb: constant_array = constant_name.split("::")
lib/bundler/vendor/molinillo/lib/molinillo/errors.rb: solver_name = opts.delete(:solver_name) { self.class.name.split('::').first }
lib/bundler/vendor/thor/lib/thor/parser/argument.rb: class_name = self.class.name.split("::").last
lib/bundler/vendor/thor/lib/thor/parser/arguments.rb: class_name = self.class.name.split("::").last.downcase
lib/optparse/version.rb: pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
lib/optparse/version.rb: path.split(/::|\//).inject(base) do |klass, name|
lib/rdoc/any_method.rb: name = @full_name.split('::')
lib/rdoc/context.rb: names = ename.split('::')
lib/rdoc/context.rb: path = [prefix] + path.split('::')
lib/rdoc/method_attr.rb: $1.split('::').last. # ClassName => class_name
lib/rdoc/parser/c.rb: ([\w\. \t]+ = \s+)?rb_define_(class|module)_under[\t\w, (]*?"(#{class_name.split('::').last})"%xm then
lib/rdoc/parser/ruby.rb: obj = name_t[:text].split("::").inject(Object) do |state, item|
lib/rdoc/store.rb: name = klass_name.split('::').last
lib/rdoc/store.rb: File.join @path, *klass_name.split('::')
lib/rdoc/store.rb: method_name = method_name.split('::').last
lib/rss/atom.rb: "#{self.class.name.split(/::/).last.downcase}="
lib/rss/atom.rb: target.__send__(self.class.name.split(/::/).last.downcase) {|x| x}
lib/rss/atom.rb: target.__send__("new_#{self.class.name.split(/::/).last.downcase}")
lib/rss/rss.rb: tag_name = klass.name.split(/::/).last
spec/bundler/support/artifice/fail.rb: const = name.split("::").reduce(Object) {|mod, sym| mod.const_get(sym) }
spec/mspec/lib/mspec/utils/name_map.rb: c.split('::').inject(base) do |dir, name|
spec/mspec/lib/mspec/utils/name_map.rb: name = mapping[c.split('::').last] || mapping.fetch(:default)
</code></pre>
<p>I think we need <code>Module#name_components</code> method that returns the array of symbols (or string, I prefer symbols) which comes from splitting name by <code>::</code>.</p> Ruby master - Bug #15764 (Open): Whitespace and control characters should not be permitted in tokenshttps://bugs.ruby-lang.org/issues/157642019-04-11T20:59:47ZBatmanAoD (Kyle Strand)kyle.j.strand@gmail.com
<p>As of Ruby 2.5.1p57, it appears that all valid Unicode code-points above 128 are permitted in tokens. This includes whitespace and control characters.</p>
<p>This was demonstrated here: <a href="https://gist.github.com/qrohlf/7045823" class="external">https://gist.github.com/qrohlf/7045823</a></p>
<p>I have attached the raw download from the above gist.</p>
<p>The issue has been discussed on StackOverflow: <a href="https://stackoverflow.com/q/34455427/1858225" class="external">https://stackoverflow.com/q/34455427/1858225</a></p>
<p>I would say this is arguably a bug, but I am marking this ticket as a "feature" since the current behavior could be considered by-design.</p> Ruby master - Feature #15445 (Open): Reject '.123' in Float() methodhttps://bugs.ruby-lang.org/issues/154452018-12-21T00:16:38Zmrkn (Kenta Murata)muraken@gmail.com
<p>Since ruby 1.8, Ruby occurs a syntax error for "." floating literal.<br>
But Float() method accepts such form now.</p>
<p>I propose to reject "." form even in Float() method.</p> Ruby master - Feature #15112 (Open): Introducing the short form of `STDERR.puts expr.inspect`.https://bugs.ruby-lang.org/issues/151122018-09-13T06:15:38Zmrkn (Kenta Murata)muraken@gmail.com
<p>I sometimes write <code>STDERR.puts obj.inspect</code> to print debug message to standard error.<br>
I want to write it as <code>STDERR.p obj</code>.<br>
It can be realized by introducing <code>p</code> singleton method in <code>STDERR</code> object.</p> Ruby master - Feature #14927 (Open): Loading multiple files at oncehttps://bugs.ruby-lang.org/issues/149272018-07-20T18:13:55ZAnonymous
<p>Just a proof concept I wanted to share. Maybe it could be useful?</p>
<p>Say you want to load all the .rb files in your lib directory:</p>
<pre><code class="ruby syntaxhl" data-language="ruby">
<span class="no">Dir</span><span class="p">[</span><span class="s1">'lib/**/*.rb'</span><span class="p">].</span><span class="nf">each</span> <span class="p">{</span> <span class="o">|</span><span class="n">file</span><span class="o">|</span> <span class="nb">load</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="p">}</span>
</code></pre>
<p>This approach may not work if your files have dependencies like that:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="c1"># lib/foo.rb</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="o"><</span> <span class="no">Bar</span>
<span class="k">end</span>
</code></pre>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="c1"># lib/bar.rb</span>
<span class="k">class</span> <span class="nc">Bar</span>
<span class="k">end</span>
</code></pre>
<p>Foo class needs Bar class. You will get a NameError (uninitialized constant Bar).</p>
<p>So in my personal projects, I use this algorithm to load all my files and to automatically take care of dependencies (class/include):</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">def</span> <span class="nf">boot</span><span class="p">(</span><span class="n">files</span><span class="p">)</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span> <span class="o"><</span> <span class="n">files</span><span class="p">.</span><span class="nf">length</span>
<span class="k">begin</span>
<span class="nb">load</span><span class="p">(</span><span class="n">files</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="k">rescue</span> <span class="no">NameError</span>
<span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">else</span>
<span class="k">while</span> <span class="n">i</span> <span class="o">></span> <span class="mi">0</span>
<span class="n">files</span><span class="p">.</span><span class="nf">push</span><span class="p">(</span><span class="n">files</span><span class="p">.</span><span class="nf">shift</span><span class="p">)</span>
<span class="n">i</span> <span class="o">-=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="n">files</span><span class="p">.</span><span class="nf">shift</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<pre><code class="ruby syntaxhl" data-language="ruby">
<span class="n">boot</span> <span class="no">Dir</span><span class="p">[</span><span class="s1">'lib/**/*.rb'</span><span class="p">]</span> <span class="c1"># It works! foo.rb and bar.rb are properly loaded.</span>
</code></pre>
<p>My point is: it would be cool if Kernel#load could receive an array of filenames (to load all these files in the proper order). So we could load all our libs with just a single line:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">load</span> <span class="no">Dir</span><span class="p">[</span><span class="s1">'{path1,path2}/**/*.rb'</span><span class="p">]</span>
</code></pre> Ruby master - Misc #14760 (Open): cross-thread IO#close semanticshttps://bugs.ruby-lang.org/issues/147602018-05-15T10:04:52Znormalperson (Eric Wong)normalperson@yhbt.net
<p>I wrote about cross-thread IO#close in ruby-core, but I'm not sure if it's a bug<br>
or not to have missing support for IO.select and IO.copy_stream:</p>
<p>IO.select -<br>
<a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/86655" class="external">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/86655</a><br>
<a href="https://public-inbox.org/ruby-core/20180423133946.GA6019@dcvr/" class="external">https://public-inbox.org/ruby-core/20180423133946.GA6019@dcvr/</a></p>
<p>IO.copy_stream -<br>
<a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/87040" class="external">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/87040</a><br>
<a href="https://public-inbox.org/ruby-core/20180515095315.GA15909@dcvr/" class="external">https://public-inbox.org/ruby-core/20180515095315.GA15909@dcvr/</a></p>
<p>I know the IO.select case in 1.9+ differs from 1.8, and IO.copy_stream wasn't in<br>
1.8, but I guess the current behavior is that it isn't consistent with normal IO<br>
methods. IO.copy_stream will also behave "normally" and raise IOError if it<br>
somehow hits non-optimized cases and ends up calling Ruby methods, but my<br>
example in <a href="https://blade.ruby-lang.org/ruby-core/87040">[ruby-core:87040]</a> did not hit that case.</p>
<p>On one hand, I'm not a fan of "nanny features" like deadlock detection for<br>
threading. On the other hand, I value consistency and we already went down the<br>
rabbit hole of supporting current users of rb_thread_io_blocking_region.</p>
<p>Anyways, I can implement these if desired since I have additional work planned<br>
in this area anyways (auto-fiber).</p> Ruby master - Feature #14724 (Open): chains of inequalitieshttps://bugs.ruby-lang.org/issues/147242018-04-30T06:36:57Zgotoken (Kentaro Goto)gotoken@gmail.com
<p>In mathematics, chain of inequations is a shorthand notation for the conjunction of several inequations involving common expressions.</p>
<p>For example, <code>a < b <= c</code> for <code>a < b && b <= c</code></p>
<p>Chain notation makes code clearer, in particular, long common expression cases will be so. E.g.,</p>
<pre><code>cur.to_i - 2 <= timeval.tv_sec <= cur.to_i
</code></pre>
<p>is easier to read than</p>
<pre><code>cur.to_i - 2 <= timeval.tv_sec && timeval.tv_sec <= cur.to_i
</code></pre>
<p>because in the latter case we have to verify whether <code>timeval.tv_sec</code> is common or not by eyes.</p>
<p>Current syntax allows but redefining builtin methods are considered not practical. So here I request as a new syntax for the chains.</p>
<a name="Use-cases-applicable-conjunctions"></a>
<h3 >Use cases (applicable conjunctions)<a href="#Use-cases-applicable-conjunctions" class="wiki-anchor">¶</a></h3>
<p>lib/matrix.rb:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="k">unless</span> <span class="mi">0</span> <span class="o"><=</span> <span class="n">column</span> <span class="o">&&</span> <span class="n">column</span> <span class="o"><</span> <span class="n">column_count</span>
</code></pre>
<p>lib/time.rb documents:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="c1"># block. For example:</span>
<span class="c1">#</span>
<span class="c1"># Time.parse(...) {|y| 0 <= y && y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}</span>
</code></pre>
<p>spec/ruby/optional/capi/bignum_spec.rb:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="k">raise</span> <span class="s2">"Bignum#coerce returned Fixnum"</span> <span class="k">if</span> <span class="n">fixnum_min</span> <span class="o"><=</span> <span class="n">n</span> <span class="o">&&</span> <span class="n">n</span> <span class="o"><=</span> <span class="n">fixnum_max</span>
</code></pre>
<p>test/fiddle/test_import.rb:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="n">assert</span><span class="p">(</span><span class="n">cur</span><span class="p">.</span><span class="nf">to_i</span> <span class="o">-</span> <span class="mi">2</span> <span class="o"><=</span> <span class="n">timeval</span><span class="p">.</span><span class="nf">tv_sec</span> <span class="o">&&</span> <span class="n">timeval</span><span class="p">.</span><span class="nf">tv_sec</span> <span class="o"><=</span> <span class="n">cur</span><span class="p">.</span><span class="nf">to_i</span><span class="p">)</span>
</code></pre>
<p>tool/jisx0208.rb:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"> <span class="k">unless</span> <span class="mh">0x8140</span> <span class="o"><=</span> <span class="n">sjis</span> <span class="o">&&</span> <span class="n">sjis</span> <span class="o"><=</span> <span class="mh">0xFCFC</span>
</code></pre> Ruby master - Feature #14546 (Open): Hash#delete!https://bugs.ruby-lang.org/issues/145462018-02-23T18:52:02Zrringler (Ryan Ringler)
<p>Hash#delete currently returns nil if a given key is not found in the hash. It would be nice to have a way to check that the key was present in the hash. This can be accomplished with with a block, but it would be nice to have some sugar for this.</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">{</span> <span class="ss">a: </span><span class="s1">'a'</span> <span class="p">}.</span><span class="nf">delete</span><span class="p">(</span><span class="ss">:b</span><span class="p">)</span> <span class="c1"># => nil</span>
<span class="p">{</span> <span class="ss">a: </span><span class="s1">'a'</span> <span class="p">}.</span><span class="nf">delete</span><span class="p">(</span><span class="ss">:b</span><span class="p">)</span> <span class="p">{</span> <span class="o">|</span><span class="n">key</span><span class="o">|</span> <span class="k">raise</span> <span class="no">KeyError</span><span class="p">,</span> <span class="s2">"key not found </span><span class="si">#{</span><span class="n">key</span><span class="si">}</span><span class="s2">"</span> <span class="p">}</span> <span class="c1"># => KeyError (key not found: b)</span>
</code></pre>
<p>I'd like to propose a Hash#delete! method:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">{</span> <span class="ss">a: </span><span class="s1">'a'</span> <span class="p">}.</span><span class="nf">delete!</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="c1"># => 'a'</span>
<span class="p">{</span> <span class="ss">a: </span><span class="s1">'a'</span> <span class="p">}.</span><span class="nf">delete!</span><span class="p">(</span><span class="ss">:b</span><span class="p">)</span> <span class="c1"># => KeyError (key not found: :b)</span>
</code></pre> Ruby master - Feature #14397 (Assigned): public, protected and private should return their argume...https://bugs.ruby-lang.org/issues/143972018-01-24T21:27:26Zusa (Usaku NAKAMURA)usa@garbagecollect.jp
<p>Matsuda-san suggested me that <code>public</code>, <code>protected</code> and <code>private</code> should return their arguments instead of <code>self</code>,<br>
to write such code:`</p>
<pre><code class="Ruby syntaxhl" data-language="Ruby"><span class="nb">require</span> <span class="s2">"finalist"</span>
<span class="c1"># see https://github.com/joker1007/finalist</span>
<span class="k">class</span> <span class="nc">Foo</span>
<span class="kp">extend</span> <span class="no">Finalist</span>
<span class="n">final</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">foo</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>I believe that it's reasonable request, and also believe that there is no product code which uses the return values of <code>public</code>, <code>protected</code> and <code>private</code>.<br>
Matz, how do you think about this change?<br>
The patch is attached.</p> Ruby master - Feature #14128 (Open): Introduce Hash#delete default valuehttps://bugs.ruby-lang.org/issues/141282017-11-23T14:18:23Zgshutler (Garry Shutler)
<p>Mirror <code>Hash#fetch(key [, default]) → obj</code> with <code>Hash#delete(key [, default]) → obj</code>.</p>
<p>Allows for more concise extraction of a value from a hash with a default.</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="c1"># Currently</span>
<span class="n">a</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="ss">:a</span><span class="p">)</span> <span class="p">{</span> <span class="mi">10</span> <span class="p">}</span>
<span class="c1"># Becomes</span>
<span class="n">a</span> <span class="o">=</span> <span class="nb">hash</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="ss">:a</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
</code></pre> Ruby master - Feature #12306 (Open): Implement String #blank? #present? and improve #strip and fa...https://bugs.ruby-lang.org/issues/123062016-04-20T23:33:04Zsam.saffron (Sam Saffron)sam.saffron@gmail.com
<p>Time and again there have been rejected feature requests to Ruby core to implement <code>blank</code> and <code>present</code> protocols across all objects as ActiveSupport does. I am fine with this call and think it is fair.</p>
<p>However, for the narrow case of String having <code>#blank?</code> and <code>#present?</code> makes sense.</p>
<ul>
<li>
<p>Provides a natural extension over <code>#strip</code>, <code>#lstrip</code> and <code>#rstrip</code>. <code>(" ".strip.length == 0) == " ".blank?</code></p>
</li>
<li>
<p>Plays nicely with ActiveSupport, providing an efficient implementation in Ruby core: see: <a href="https://github.com/SamSaffron/fast_blank" class="external">https://github.com/SamSaffron/fast_blank</a>, implementing blank efficiently requires a c extension.</p>
</li>
</ul>
<p>However, if this work is to be done, <code>#strip</code> and should probably start dealing with unicode blanks, eg:</p>
<pre><code>irb(main):008:0> [0x3000].pack("U")
=> " "
irb(main):009:0> [0x3000].pack("U").strip.length
=> 1
</code></pre>
<p>So there are 2 questions / feature requests here</p>
<ol>
<li>Can we add blank? and present? to String?</li>
<li>Can we amend strip and family to account for unicode per: <a href="https://github.com/SamSaffron/fast_blank/blob/master/ext/fast_blank/fast_blank.c#L43-L74" class="external">https://github.com/SamSaffron/fast_blank/blob/master/ext/fast_blank/fast_blank.c#L43-L74</a>
</li>
</ol> Ruby master - Feature #12244 (Open): Add a way to `integer - integer % num`https://bugs.ruby-lang.org/issues/122442016-04-02T13:45:33Znaruse (Yui NARUSE)naruse@airemix.jp
<p>We sometimes calculates <code>integer - integer % num</code>.</p>
<p>For example time series events into time partitions, we write code like</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">event</span> <span class="c1"># {time: 1459580435, name: "hoge", text: "Rawr!"}</span>
<span class="n">partition</span> <span class="o">=</span> <span class="n">event</span><span class="p">[</span><span class="ss">:time</span><span class="p">]</span> <span class="o">-</span> <span class="n">event</span><span class="p">[</span><span class="ss">:time</span><span class="p">]</span> <span class="o">%</span> <span class="n">num</span>
<span class="n">chunk</span> <span class="o">=</span> <span class="n">get_chunk</span><span class="p">(</span><span class="n">partition</span><span class="p">)</span>
<span class="n">chunk</span><span class="p">.</span><span class="nf">write</span> <span class="n">event</span>
</code></pre>
<p><a href="https://twitter.com/tagomoris/status/715814050534461440" class="external">https://twitter.com/tagomoris/status/715814050534461440</a><br>
<a href="https://twitter.com/tagomoris/status/715814961260457985" class="external">https://twitter.com/tagomoris/status/715814961260457985</a></p>
<p>The name is always issue.<br>
There are some suggestions likes Integer#adjust](<a href="https://twitter.com/cocoatomo/status/716088708655489024" class="external">https://twitter.com/cocoatomo/status/716088708655489024</a>).</p>
<p>kosaki says <a href="https://twitter.com/kosaki55tea/status/716059296186765312" class="external">Excel's FLOOR() function is FLOOR(number, significance)</a>.<br>
Therefore Ruby should be <a href="https://twitter.com/kosaki55tea/status/716106530114768897" class="external">Integer#floor(digits=1, significance: nil)</a>.<br>
<a href="https://twitter.com/kosaki55tea/status/716107516409581568" class="external">kosaki agrees this</a>.</p>
<p>I checked the speed of a half baked implementation..., but it's 10x slow...</p>
<pre><code>% time ./miniruby -e'i=10000000;while i>0;i-=1;1459497599.floor(significance: 3600);end'
./miniruby 6.58s user 0.02s system 99% cpu 6.596 total
#3 1459604131 22:35:31 naruse@windy:~/obj/ruby
% time ./miniruby -e'i=10000000;while i>0;i-=1;t=1459497599;t-t%3600;end'
./miniruby -e'i=10000000;while i>0;i-=1;t=1459497599;t-t%3600;end' 0.52s user 0.00s system 99% cpu 0.520 total
</code></pre>
<pre><code class="diff syntaxhl" data-language="diff"><span class="gh">diff --git a/numeric.c b/numeric.c
index 37217a1..f6acfe3 100644
</span><span class="gd">--- a/numeric.c
</span><span class="gi">+++ b/numeric.c
</span><span class="p">@@ -4123,6 +4123,42 @@</span> int_dotimes(VALUE num)
<span class="err">
</span> /*
* call-seq:
<span class="gi">+ * int.floor([ndigits]) -> integer or float
+ *
+ * Rounds +int+ to a given precision in decimal digits (default 0 digits).
+ *
+ * Precision may be negative. Returns a floating point number when +ndigits+
+ * is positive, +self+ for zero, and round down for negative.
+ *
+ * 1.round #=> 1
+ * 1.round(2) #=> 1.0
+ * 15.round(-1) #=> 20
+ */
+
+static VALUE
+int_floor(int argc, VALUE* argv, VALUE num)
+{
+ static ID keyword_ids[1];
+ VALUE kwargs[1], ndigits, opt;
+ if (!keyword_ids[0]) {
+ CONST_ID(keyword_ids[0], "significance");
+ }
+
+ rb_scan_args(argc, argv, "01:", &ndigits, &opt);
+ if (!NIL_P(opt)) {
+ VALUE factor;
+ long a, b;
+ rb_get_kwargs(opt, keyword_ids, 0, 1, kwargs);
+ factor = kwargs[0];
+ a = FIX2LONG(num);
+ b = FIX2LONG(factor);
+ return LONG2FIX(a - a % b);
+ }
+ return Qnil;
+}
+
+/*
+ * call-seq:
</span> * int.round([ndigits]) -> integer or float
*
* Rounds +int+ to a given precision in decimal digits (default 0 digits).
<span class="p">@@ -4321,7 +4357,7 @@</span> Init_Numeric(void)
rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
<span class="gd">- rb_define_method(rb_cInteger, "floor", int_to_i, 0);
</span><span class="gi">+ rb_define_method(rb_cInteger, "floor", int_floor, -1);
</span> rb_define_method(rb_cInteger, "ceil", int_to_i, 0);
rb_define_method(rb_cInteger, "truncate", int_to_i, 0);
rb_define_method(rb_cInteger, "round", int_round, -1);
</code></pre> Ruby master - Feature #11735 (Open): Porting String#squish and String#squish! from Ruby on Rails'...https://bugs.ruby-lang.org/issues/117352015-11-24T19:36:33Zsikachu (Prem Sichanugrist)s+ruby@sikac.hu
<p>Hi,</p>
<p>I have been using this <code>String#squish</code> method so many time when I'm using Rails, and I think it should be a useful addition to core.</p>
<p>Here's the method on Rails' documentation: <a href="http://api.rubyonrails.org/v4.2.5/classes/String.html#method-i-squish" class="external">http://api.rubyonrails.org/v4.2.5/classes/String.html#method-i-squish</a></p>
<p>This method is very useful when you have to write a multi-line string using heredoc, but you actually does not care about the white-spaces before, after, and in-between the string.</p>
<p>For example:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="o"><<-</span><span class="no">SQL</span><span class="p">.</span><span class="nf">squish</span><span class="sh">
SELECT *
FROM users
WHERE users.username = 'sikachu'
</span><span class="no">SQL</span>
<span class="c1">#=> "SELECT * FROM users WHERE users.username='sikachu'"</span>
</code></pre>
<p>Another example usage is when you are on the project that have a line length code standard, and you have to write a long warning message that needs to be printed to stdout:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">puts</span> <span class="o"><<-</span><span class="no">WARNING</span><span class="p">.</span><span class="nf">squish</span><span class="sh">
Unable to connect to the server. Please double-check that you are currently
connecting to the internet and your proxy server is working.
</span><span class="no">WARNING</span>
<span class="c1">#=> Unable to connect to the server. Please double-check that you are currently connecting to the internet and your proxy server is working.</span>
</code></pre>
<p>By the way, this is my first patch and my first time writing something in C, so there might be something that does not look right to you. I'll happy to revise this patch (and learn about C in the process!) from your feedback.</p>
<p>Thank you,<br>
Prem</p> Ruby master - Feature #11518 (Open): Queue enhancement - promote! and promote_all!https://bugs.ruby-lang.org/issues/115182015-09-09T15:04:58Zjonathanscruz (Jonathan Cruz)jonathanscruz@yahoo.com
<p>I’m submitting a patch to enhance the Queue class by adding the methods Queue#promote! and Queue#promote_all!. These methods require a block that accepts queue elements. Elements for which the block returns a truthy value are moved to the ‘front’ of the queue. Queue#promote! only applies to the first such element and Queue#promote_all! applies to all matching elements (preserving their relative order).</p>
<p>Motivation for this enhancement: Our project has several worker threads working on long-running work units in a queue, trying to find a ‘match’. The queue is pre-sorted with the most likely matches at the front and least likely at the back. However, there are cases where as we work on some elements, we gain new data that certain elements are more likely to match than we originally thought. We need a way to promote these elements to the front of the queue.</p> Ruby master - Feature #11517 (Open): Queue enhancement - conditional pophttps://bugs.ruby-lang.org/issues/115172015-09-09T15:03:32Zjonathanscruz (Jonathan Cruz)jonathanscruz@yahoo.com
<p>I’m submitting a patch to enhance Queue#pop. This allows the caller to provide a block that accepts data from the queue. Queue#pop will return the first element for which the block returns a truthy value, and remove it from the queue. Without a block, Queue#pop will behave the same way it currently does.</p>
<p>The motivation for this enhancement: On our project, we have a queue of work and several worker threads. Some work can incur a heavy load on the system and should not be processed while another worker is processing 'heavy load' work. We need a way for Queue#pop to skip over heavy load items while another thread is processing heavy load work.</p> Ruby master - Feature #11390 (Open): Allow symbols starting with numbershttps://bugs.ruby-lang.org/issues/113902015-07-22T19:32:50Zv0dro (Sameer Deshmukh)sameer.deshmukh93@gmail.com
<p>Currently it is not possible to create a symbol that looks like <code>:1twothree</code>.</p>
<p>Converting to a string and then symbolizing causes hash lookup problems and proves counter-intuitive. What's also surprising is that ruby allows symbols to start with special characters but not numbers.</p> Ruby master - Feature #11307 (Open): exception-free non-blocking Queue#pophttps://bugs.ruby-lang.org/issues/113072015-06-25T23:06:21Znormalperson (Eric Wong)normalperson@yhbt.net
<p>As we learned from the nonblocking IO APIs, exceptions are noisy with debugging<br>
enabled and waste allocations on backtraces. We should have a better way to do<br>
non-blocking Queue#pop without raising exceptions, but I don't know what the API<br>
should be...</p> Ruby master - Feature #11181 (Open): Add a line directive to Rubyhttps://bugs.ruby-lang.org/issues/111812015-05-26T07:05:18Zgam3 (Allen Morris)gam3-ruby@gam3.net
<p>Add a <strong>line directive</strong> to Ruby</p>
<pre><code> #line {nn} ["filename"]
</code></pre>
<p>This is done by creating a array of filenames and using the upper bits of the line_number to determine the current filename. The original filename is in position 0.</p>
<p>An extra node is added by the parser that informs the compiler of the filenames so the backtrace code can also use the correct file names.</p>
<p>The <strong>__LINE</strong>__ and <strong>__FILE</strong>__ <em>constants</em> are updated and compile time warnings are also effected.</p>
<p>There is a pull request at <a href="https://github.com/ruby/ruby/pull/911" class="external">https://github.com/ruby/ruby/pull/911</a></p>
<p>The patch does not have any affect on current programs unless a line matching '#\s<em>line \d+(\s+"(.</em>)")?\s*$' is found in the ruby source code.</p>
<p>More tests need to be written before this change sould be applied.</p>
<p>Use case:</p>
<p>This is helpful for debugging any generated code but is particularlly helpful for literate programming using Noweb.</p> Ruby master - Feature #11122 (Open): exception-free non-blocking Queue/SizedQueue operationshttps://bugs.ruby-lang.org/issues/111222015-05-06T20:53:09Znormalperson (Eric Wong)normalperson@yhbt.net
<p>I would like to reduce exceptions for non-blocking operations on<br>
Queue/SizedQueue in the same way we are reducing exceptions for non-blocking<br>
I/O with *_nonblock(..., exception: false) methods.</p>
<p>However, I'm unclear what the API would be, since queues return Ruby objects<br>
instead of String buffers or number of bytes written, so any special<br>
object/symbol we would return could conflict with existing applications.</p>
<p>Perhaps something like:</p>
<pre><code>queue.pop(nonblock: :WAIT)
queue.push(obj, nonblock: :WAIT)
</code></pre>
<p>Which would allow user to specify which object to raise when a queue is empty<br>
or full (similar to Timeout.timeout allowing specific exception to raise).</p> Ruby master - Feature #11028 (Assigned): standalone running single file ( zipped archives of ruby...https://bugs.ruby-lang.org/issues/110282015-04-03T03:44:09Zzaxebo1 (zaxebo zaxebo)zaxebo1@gmail.com
<p>standalone running single file ( zipped archives of ruby code) running <strong>without installation</strong> using "gem install ..."<br>
prior examples in other languages:</p>
<pre><code>python myprg.pyz
java -jar myprg.jar
</code></pre>
<a name="Detailed-Description"></a>
<h2 >Detailed Description:<a href="#Detailed-Description" class="wiki-anchor">¶</a></h2>
<p>In python, if i have multiple program files: "<code>a1.py</code>, <code>a2.py</code>, <code>__main__.py</code>,<br>
<code>dir1/b1.py</code>, <code>dir1/b2.py</code>" and then i zip it as myprogram1.pyz<br>
then i can run it as "python myprogram.pyz" (<code>__main__.py</code> inside the zip<br>
file will be executed first). It is easy to distribute a single file<br>
myprogram1.pyz</p>
<p>see: <a href="http://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/" class="external">http://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/</a></p>
<hr>
<p>in java also we can bundle all the .class files into a single .jar file<br>
and run it</p>
<pre><code>java -jar myprogram1.jar
</code></pre>
<hr>
<p>Currently in ruby the ".gem" file requires installation using "gem install ...". Then it gives some program file for running.<br>
What i am asking is that some gem file should have manifest with which they can run directly without installing</p>
<p>That is, i request you to kind provide a feature in ruby that if i have lots of files like: <code>a1.rb</code>, <code>a2.rb</code>, <code>__main__.rb</code>, <code>dir1/a4.rb</code> etc.<br>
(say, which uses Ruby-GTK for a Desktop application). Then i should be able to bundle them as zip file, say myprog1.zip or myprog1.pz ( rbz=ruby's zipped executable archive).<br>
And then i can distribute this "single file" and execute it as:</p>
<pre><code>ruby myprog1.rbz
</code></pre>
<p>This will execute the <code>__main__.rb</code> file among all the other .rb files,<br>
inside this .zip archive myprog1.rbz .<br>
Note: this .rbz file extension can be .gemz or whatever, but this functionality of "standalone running zipped archives of ruby code running without installation" is essential</p> Ruby master - Feature #10574 (Open): Add String#lchomp and String.lchomp!https://bugs.ruby-lang.org/issues/105742014-12-05T20:37:41Zjavawizard (Alex Boyd)alex@opengroove.org
<p>With the expected behavior, i.e.</p>
<pre><code>irb(main):013:0> 'foobar'.lchomp('foo')
=> "bar"
irb(main):014:0> 'foobar'.lchomp('baz')
=> "foobar"
</code></pre>
<p>A quick google search will turn up plenty of practical uses for this, as well as lots of libraries that patch <code>String</code> themselves to add this.</p> Ruby master - Misc #10541 (Open): Remove shorthand string interpolation syntaxhttps://bugs.ruby-lang.org/issues/105412014-11-25T16:15:58Zdanielmorrison (Daniel Morrison)daniel@collectiveidea.com
<p>I would like to see the shorthand string interpolation syntax, "foo#@bar" deprecated and then removed in 3.0.</p>
<p>My reasons:</p>
<ol>
<li>Most experienced Ruby developers I've talked to don't even know it exists.</li>
<li>It has been the cause of real problems. <a href="http://status.cloudamqp.com/incidents/vj62pnp62tj9" class="external">http://status.cloudamqp.com/incidents/vj62pnp62tj9</a>
</li>
</ol>
<p>When a syntax is not widely known and has the potential for problems, I think it makes sense to deprecate and remove.</p> Ruby master - Feature #10498 (Open): Make `loop` yield a counterhttps://bugs.ruby-lang.org/issues/104982014-11-12T06:33:46Zcesario (Franck Verrot)franck@verrot.fr
<a name="Problem"></a>
<h1 >Problem<a href="#Problem" class="wiki-anchor">¶</a></h1>
<p>Teaching Ruby, we always end up with that type of construct</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="kp">loop</span> <span class="k">do</span>
<span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="c1"># do something with i....</span>
<span class="k">raise</span> <span class="no">StopIteration</span> <span class="k">if</span> <span class="n">i</span> <span class="o">...</span>
<span class="k">end</span>
</code></pre>
<a name="Solution"></a>
<h1 >Solution<a href="#Solution" class="wiki-anchor">¶</a></h1>
<p>What I propose with this patch is making <code>loop</code> yield the iteration count:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="kp">loop</span> <span class="k">do</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span>
<span class="c1"># do something with i....</span>
<span class="k">raise</span> <span class="no">StopIteration</span> <span class="k">if</span> <span class="n">i</span> <span class="o">...</span>
<span class="k">end</span>
</code></pre>
<p><code>i</code> starts at 0 and stops at <code>FIXNUM_MAX</code> (there's no <code>Float::Infinity</code> equivalent for integers).</p>
<a name="Alternate-solution"></a>
<h1 >Alternate solution<a href="#Alternate-solution" class="wiki-anchor">¶</a></h1>
<p><code>Integer#times</code> could work if we had an <code><Integer's infinity></code> object, so we would just do <code><Integer's Infinity>.times { |i| ... }</code>.</p>
<p>Also, this is the very first patch I submit to Ruby, I might have done something horrible, feel free to tell me :-)</p> Ruby master - Feature #10481 (Assigned): Add "if" and "unless" clauses to rescue statementshttps://bugs.ruby-lang.org/issues/104812014-11-05T19:20:10Zjavawizard (Alex Boyd)alex@opengroove.org
<p>I'd like to propose a syntax change: allow boolean "if" and "unless" clauses to follow a rescue statement.</p>
<p>Consider the following:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">begin</span>
<span class="o">...</span>
<span class="k">rescue</span> <span class="no">SomeError</span> <span class="o">=></span> <span class="n">e</span>
<span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">error_code</span> <span class="o">==</span> <span class="mi">1</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span><span class="o">...</span>
<span class="k">else</span>
<span class="k">raise</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>This is a fairly common way of dealing with exceptions where some condition above and beyond the exception's type determines whether the exception should be rescued. It's verbose, though, and it's not obvious at first glance exactly what conditions are being rescued, especially if "...handle error..." is more than a few lines long. I propose that the following be allowed:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">begin</span>
<span class="o">...</span>
<span class="k">rescue</span> <span class="no">SomeError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">error_code</span> <span class="o">==</span> <span class="mi">1</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span><span class="o">...</span>
<span class="k">end</span>
</code></pre>
<p>"unless" would, of course, be allowed as well:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">begin</span>
<span class="o">...</span>
<span class="k">rescue</span> <span class="no">SomeError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">unless</span> <span class="n">e</span><span class="p">.</span><span class="nf">error_code</span> <span class="o">==</span> <span class="mi">2</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span><span class="o">...</span>
<span class="k">end</span>
</code></pre>
<p>A rescue statement whose boolean condition failed would be treated the same as if the exception being raised didn't match the exception being rescued, and move on to the next rescue statement:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">begin</span>
<span class="o">...</span>
<span class="k">rescue</span> <span class="no">SomeError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">error_code</span> <span class="o">==</span> <span class="mi">1</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span> <span class="n">code</span> <span class="mi">1</span><span class="o">...</span>
<span class="k">rescue</span> <span class="no">SomeError</span> <span class="o">=></span> <span class="n">e</span> <span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">error_code</span> <span class="o">==</span> <span class="mi">2</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span> <span class="n">code</span> <span class="mi">2</span><span class="o">...</span>
<span class="k">end</span>
</code></pre>
<p>And finally, catch-all rescue statements would be allowed as well:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">begin</span>
<span class="o">...</span>
<span class="k">rescue</span> <span class="o">=></span> <span class="n">e</span> <span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">message</span> <span class="o">==</span> <span class="s2">"some error"</span>
<span class="o">...</span><span class="n">handle</span> <span class="n">error</span><span class="o">...</span>
<span class="k">end</span>
</code></pre> Ruby master - Feature #10404 (Open): Allow individual finalizers to be removed with ObjectSpace.u...https://bugs.ruby-lang.org/issues/104042014-10-20T08:14:36Zjavawizard (Alex Boyd)alex@opengroove.org
<p>Pretty self-explanatory: allow removal of individual define_finalizer blocks without removing all of them as undefine_finalizer currently does.</p>
<p>From an API standpoint, this could be done by having define_finalizer return some sort of unique value (maybe an integer, or perhaps the type is unspecified), and this value could then be passed as undefine_finalizer's second argument to remove just that finalizer.</p> Ruby master - Feature #9816 (Assigned): 文字列内の数字を数値として比較するメソッドhttps://bugs.ruby-lang.org/issues/98162014-05-08T09:37:26Znaruse (Yui NARUSE)naruse@airemix.jp
<p>文字列内の数字を数値として比較するメソッドを追加しませんか</p>
<p>そのような比較は一般的な用途としてはGUIシェルのファイラーが比較に用いており、<br>
Windows では StrCmpLogicalW が、OS X では NSString:compare:options:へのNSNumericSearch定数が提供されています。<br>
<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb759947(v=vs.85).aspx" class="external">http://msdn.microsoft.com/en-us/library/windows/desktop/bb759947(v=vs.85).aspx</a><br>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSNumericSearch" class="external">https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSNumericSearch</a></p>
<p>上記のような処理自体はさほど難しいものではありませんが、Rubyレベルで実装すると大量のオブジェクトを作ってしまいます。<br>
例えば <code>Gem::Version.new("2.1.10".freeze)<=>Gem::Version.new("2.1.9".freeze)</code> は47個、<br>
<code>"2.1.10".freeze.split('.').map(&:to_i)<=>"2.1.9".freeze.split('.').map(&:to_i)</code> だと16個のオブジェクトを作ります。<br>
<code>"2.1.10".freeze.numericcmp"2.1.9".freeze</code> ならば、もちろんオブジェクトは一つも作りません。</p>
<p>なお、上記の例でも示唆していますが、本メソッドは Ruby のバージョン表記の TEENY が2桁になった場合の比較に用いることができます。</p>
<p>パッチは以下の通りです。<br>
なお、メソッド名は String#numericcmp としています。<br>
(String#casecmpを念頭に置いた)</p>
<pre><code>diff --git a/string.c b/string.c
index c589c80..66f667f 100644
--- a/string.c
+++ b/string.c
@@ -2569,6 +2569,131 @@ rb_str_casecmp(VALUE str1, VALUE str2)
return INT2FIX(-1);
}
+VALUE
+numerical_compare(const char **pp1, const char *p1end, const char **pp2, const char *p2end)
+{
+ const char *s1 = *pp1, *p1, *s2 = *pp2, *p2;
+ ptrdiff_t len1, len2;
+ int r;
+
+ while (s1 < p1end && *s1 == '0') s1++;
+ p1 = s1;
+ while (p1 < p1end && ISDIGIT(*p1)) p1++;
+ len1 = p1 - s1;
+
+ while (s2 < p2end && *s2 == '0') s2++;
+ p2 = s2;
+ while (p2 < p2end && ISDIGIT(*p2)) p2++;
+ len2 = p2 - s2;
+
+ if (len1 != len2) {
+ return INT2FIX(len1 < len2 ? -1 : 1);
+ }
+
+ r = memcmp(s1, s2, len1);
+ if (r) return r < 0 ? INT2FIX(-1) : INT2FIX(1);
+
+ len1 = s1 - *pp1;
+ len2 = s2 - *pp2;
+ if (len1 != len2) {
+ return INT2FIX(len1 < len2 ? -1 : 1);
+ }
+
+ *pp1 = p1;
+ *pp2 = p2;
+ return Qnil;
+}
+
+/*
+ * call-seq:
+ * str.numericcmp(other_str) -> -1, 0, +1 or nil
+ *
+ * Variant of <code>String#<=></code>, which considers digits in strings
+ * are numeric value..
+ *
+ * "a1".numericcmp("a1") #=> 0
+ * "aa".numericcmp("a1") #=> 1
+ * "a1".numericcmp("aa") #=> -1
+ * "a1".numericcmp("a01") #=> -1
+ * "2.1.2".numericcmp("2.1.10") #=> 1
+ */
+
+static VALUE
+rb_str_numericcmp(VALUE str1, VALUE str2)
+{
+ long len;
+ rb_encoding *enc;
+ const char *p1, *p1end, *p2, *p2end;
+
+ StringValue(str2);
+ enc = rb_enc_compatible(str1, str2);
+ if (!enc) {
+ return Qnil;
+ }
+
+ p1 = RSTRING_PTR(str1); p1end = RSTRING_END(str1);
+ p2 = RSTRING_PTR(str2); p2end = RSTRING_END(str2);
+ if (single_byte_optimizable(str1) && single_byte_optimizable(str2)) {
+ while (p1 < p1end && p2 < p2end) {
+ if (ISDIGIT(*p1)) {
+ if (ISDIGIT(*p2)) {
+ VALUE r = numerical_compare(&p1, p1end, &p2, p2end);
+ if (!NIL_P(r)) return r;
+ }
+ else {
+ return INT2FIX(-1);
+ }
+ }
+ else if (ISDIGIT(*p2)) {
+ return INT2FIX(1);
+ }
+ if (*p1 != *p2) return INT2FIX(*p1 < *p2 ? -1 : 1);
+ p1++;
+ p2++;
+ }
+ }
+ else {
+ while (p1 < p1end && p2 < p2end) {
+ int l1, c1 = rb_enc_ascget(p1, p1end, &l1, enc);
+ int l2, c2 = rb_enc_ascget(p2, p2end, &l2, enc);
+
+ if (0 <= c1 && 0 <= c2) {
+ if (ISDIGIT(*p1)) {
+ if (ISDIGIT(*p2)) {
+ VALUE r = numerical_compare(&p1, p1end, &p2, p2end);
+ if (!NIL_P(r)) return r;
+ }
+ else {
+ return INT2FIX(-1);
+ }
+ }
+ else if (ISDIGIT(*p2)) {
+ return INT2FIX(1);
+ }
+ if (*p1 != *p2) return INT2FIX(*p1 < *p2 ? -1 : 1);
+ p1++;
+ p2++;
+ }
+ else {
+ int r;
+ l1 = rb_enc_mbclen(p1, p1end, enc);
+ l2 = rb_enc_mbclen(p2, p2end, enc);
+ len = l1 < l2 ? l1 : l2;
+ r = memcmp(p1, p2, len);
+ if (r != 0)
+ return INT2FIX(r < 0 ? -1 : 1);
+ if (l1 != l2)
+ return INT2FIX(l1 < l2 ? -1 : 1);
+ }
+ p1 += l1;
+ p2 += l2;
+ }
+ }
+ if (RSTRING_LEN(str1) == RSTRING_LEN(str2)) return INT2FIX(0);
+ if (RSTRING_LEN(str1) > RSTRING_LEN(str2)) return INT2FIX(1);
+ return INT2FIX(-1);
+}
+
static long
rb_str_index(VALUE str, VALUE sub, long offset)
{
@@ -8721,6 +8846,7 @@ Init_String(void)
rb_define_method(rb_cString, "eql?", rb_str_eql, 1);
rb_define_method(rb_cString, "hash", rb_str_hash_m, 0);
rb_define_method(rb_cString, "casecmp", rb_str_casecmp, 1);
+ rb_define_method(rb_cString, "numericcmp", rb_str_numericcmp, 1);
rb_define_method(rb_cString, "+", rb_str_plus, 1);
rb_define_method(rb_cString, "*", rb_str_times, 1);
rb_define_method(rb_cString, "%", rb_str_format_m, 1);
diff --git a/test/ruby/test_string.rb b/test/ruby/test_string.rb
index 8366424..f9c788b 100644
--- a/test/ruby/test_string.rb
+++ b/test/ruby/test_string.rb
@@ -2104,6 +2104,29 @@ class TestString < Test::Unit::TestCase
assert_equal(1, "\u3042B".casecmp("\u3042a"))
end
+ def test_numericcmp
+ assert_equal(-1, "2.1.0".numericcmp("2.1.1"))
+ assert_equal(-1, "2.1.9".numericcmp("2.1.10"))
+ assert_equal( 0, "a1".numericcmp("a1"))
+ assert_equal( 1, "aa".numericcmp("a1"))
+ assert_equal(-1, "a1".numericcmp("aa"))
+ assert_equal(-1, "a1".numericcmp("a01"))
+ assert_equal(-1, "a0001".numericcmp("a00001"))
+ assert_equal( 0, "a1a".numericcmp("a1a"))
+ assert_equal( 1, "a1b".numericcmp("a1a"))
+ assert_equal(-1, "a9a".numericcmp("a10a"))
+ assert_equal( 1, "b".numericcmp("a"))
+ assert_equal( 0, "\u30421".numericcmp("\u30421"))
+ assert_equal( 1, "\u3042\u3042".numericcmp("\u30421"))
+ assert_equal(-1, "\u30421".numericcmp("\u3042\u3042"))
+ assert_equal(-1, "\u30421".numericcmp("\u304201"))
+ assert_equal(-1, "\u30420001".numericcmp("\u304200001"))
+ assert_equal( 0, "\u30421\u3042".numericcmp("\u30421\u3042"))
+ assert_equal( 1, "\u30421\u3044".numericcmp("\u30421\u3042"))
+ assert_equal(-1, "\u30429\u3042".numericcmp("\u304210\u3042"))
+ assert_equal( 1, "\u3044".numericcmp("\u3042"))
+ end
+
def test_upcase2
assert_equal("\u3042AB", "\u3042aB".upcase)
end
</code></pre> Ruby master - Feature #9768 (Assigned): Method that is visible only within a certain module/classhttps://bugs.ruby-lang.org/issues/97682014-04-22T09:57:35Zsawa (Tsuyoshi Sawada)
<p>Some frameworks/libraries monkeypatch their own methods on Ruby core classes like <code>String</code>, <code>Hash</code>, <code>Array</code>, etc., and that is often causing problems/concerns of name conflict.</p>
<p>Seeing that these custom methods are used only in the context of a certain module/class, I request for a way to define a method (<code>foo</code>) on a module/class (<code>A</code>) so that it will be visible only from within a specified module/class (<code>B</code>) or its descendants. The following illustrates this situation:</p>
<pre><code>A.new.foo # => undefined
class B
A.new.foo # => defined
def bar
A.new.foo # => defined
end
def self.baz
A.new.foo # => defined
end
end
class C < B
A.new.foo # => defined
def bar
A.new.foo # => defined
end
def self.baz
A.new.foo # => defined
end
end
</code></pre>
<p>I do not have a certain syntax for this in mind, but I think it can be made much simpler, compared to the complicated syntax of refinement.</p>
<p>This is reminiscent of refinement, but they are pretty much different.</p>
<p>Refinement's purpose is to let certain methods be accessible from only a certain file. A typical use case would be a library developer defining their methods to be used from within the library and making such methods inaccessible from the end user.</p>
<p>On the other hand, the idea I am proposing here is for making method accessible from any file, but only within a certain module/class. A typical use case would be defining a method to be used by an end user, but only from within a context of certain module/class.</p> Ruby master - Feature #9704 (Open): Refinements as files instead of moduleshttps://bugs.ruby-lang.org/issues/97042014-04-04T20:41:06Ztrans (Thomas Sawyer)
<p>If refinements are to remain file-scoped, then it would be more convenient if <code>using</code> worked at the file level, akin to <code>require</code>, rather than behave like a module <code>include</code>. For instance, instead of:</p>
<pre><code># foo.rb
module Foo
refine String do
def some_method
...
end
end
end
</code></pre>
<pre><code>require 'foo'
using Foo
</code></pre>
<p>We could do:</p>
<pre><code># foo.rb
class String
def some_method
...
end
end
</code></pre>
<pre><code>using 'foo'
</code></pre>
<p>This would make <code>require</code> and <code>using</code>, in a certain sense, <em>polymorphic</em> --if we <code>require</code> it will extend the classes directly, but if <code>using</code> then they will be refined instead.</p> Ruby master - Feature #9614 (Open): ordering of non-Hash items which use st_ internallyhttps://bugs.ruby-lang.org/issues/96142014-03-09T02:25:28Znormalperson (Eric Wong)normalperson@yhbt.net
<p>Hi matz, I would like your permission to remove the order preservation from<br>
any or all of the following currently implemented using <code>st_table</code>:</p>
<ul>
<li>method tables</li>
<li>global symbols (<code>Symbol.all_symbols</code>)</li>
<li>constant tables</li>
<li>instance variable tables</li>
<li>
<code>global_variables</code> method</li>
<li><code>Thread#keys</code></li>
<li>anything besides the <code>Hash</code> class</li>
</ul>
<p>I am currently working on a patch series to reduce internal memory usage,<br>
so far I have only converted three pieces:</p>
<ol>
<li>method tables (~200K reduction)</li>
<li>symbol table (<code>global_symbols.</code>{<code>id_str</code>,<code>sym_id</code>}) (~200K)</li>
<li>
<code>frozen_strings</code> (~100K)</li>
</ol>
<p>n.b. <code>frozen_strings</code> ordering is never exposed to users, so I expect<br>
it to be OK.</p>
<p>Memory reduction is just based on "<code>ruby -e exit</code>" (which loads RubyGems);<br>
bigger programs with more methods/symbols will save more memory.</p>
<p>Work-in-progress patches attached (0002 describes implementation details)</p> Ruby master - Feature #9123 (Open): Make Numeric#nonzero? behavior consistent with Numeric#zero?https://bugs.ruby-lang.org/issues/91232013-11-19T03:12:47Zsferik (Erik Michaels-Ober)sferik@gmail.com
<p>Numeric#zero? returns true or false, while Numeric#nonzero? returns self or nil.</p>
<p>I've written a patch that fixes this inconsistency and adds a Numeric#nonzero (non-predicate) method that returns self or nil for chaining comparisons. I'd like for this to be included in Ruby 2.1.0.</p>
<p><a href="https://github.com/ruby/ruby/pull/452.patch" class="external">https://github.com/ruby/ruby/pull/452.patch</a></p> Ruby master - Feature #9070 (Open): Introduce `---` as synonym of `end` keywordhttps://bugs.ruby-lang.org/issues/90702013-11-01T23:17:58Zalexeymuranov (Alexey Muranov)
<p>=begin<br>
This is just an idea: introduce "(({---}))" as synonym of "(({end}))" keyword.</p>
<p>It is a bit easier to type and to read, and makes whitespace insensitive language look as if it follows off-side rule. Compare:</p>
<h2>class Person<br>
attr_reader :name, :age<br>
def initialize(name, age)<br>
@name, @age = name, age<br>
---<br>
def <=>(person) # the comparison operator for sorting<br>
age <=> person.age<br>
---<br>
def to_s<br>
"#{name} (#{age})"<br>
---</h2>
<p>class Person<br>
attr_reader :name, :age<br>
def initialize(name, age)<br>
@name, @age = name, age<br>
end<br>
def <=>(person) # the comparison operator for sorting<br>
age <=> person.age<br>
end<br>
def to_s<br>
"#{name} (#{age})"<br>
end<br>
end</p>
<p>=end</p> 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 #8850 (Assigned): Convert Rational to decimal stringhttps://bugs.ruby-lang.org/issues/88502013-09-02T10:02:36Znaruse (Yui NARUSE)naruse@airemix.jp
<p>On Ruby 2.1.0, decimal literal is introduced.<br>
It generates Rational but it cannot easily convert to decimal string.<br>
You know, Rational#to_f is related to this but</p>
<ul>
<li>
<p>Float is not exact number<br>
** 0.123456789123456789r.to_f.to_s #=> "0.12345678912345678"</p>
</li>
<li>
<p>it can't handle recursive decimal<br>
** (151/13r).to_f.to_s #=> "11.615384615384615"</p>
</li>
<li>
<p>the method name<br>
** to_decimal<br>
** to_decimal_string<br>
** to_s(format: :decimal)<br>
** extend sprintf</p>
</li>
<li>
<p>how does it express recursive decimal<br>
** (151/13r).to_decimal_string #=> "11.615384..."<br>
** (151/13r).to_decimal_string #=> "11.(615384)"</p>
</li>
</ul>
<p>Example implementation is following.<br>
Its result is<br>
** 0.123456789123456789r.to_f.to_s #=> "0.123456789123456789"<br>
** (151/13r).to_f.to_s #=> "11.(615384)"</p>
<pre><code>class Rational
def to_decimal_string(base=10)
n = numerator
d = denominator
r, n = n.divmod d
str = r.to_s(base)
return str if n == 0
h = {}
str << '.'
n *= base
str.size.upto(Float::INFINITY) do |i|
r, n = n.divmod d
if n == 0
str << r.to_s(base)
break
elsif h.key? n
str[h[n], 0] = '('
str << ')'
break
else
str << r.to_s(base)
h[n] = i
n *= base
end
end
str
end
end
</code></pre> Ruby master - Feature #8839 (Assigned): Class and module should return the class or module that w...https://bugs.ruby-lang.org/issues/88392013-08-31T02:57:19Zheadius (Charles Nutter)headius@headius.com
<p>With the change for <a href="https://bugs.ruby-lang.org/issues/3753" class="external">https://bugs.ruby-lang.org/issues/3753</a>, "def" forms now return the symbolic name of the method defined. Because class and module bodies just return the last expression in their bodies, this means they will now usually end up returning a symbol for the last method defined. This does not seem useful or correct.</p>
<p>I think class and module should return a reference to the class or module just opened. This would make the return value useful and consistent.</p> Ruby master - Feature #8678 (Assigned): Allow invalid string to work with regexphttps://bugs.ruby-lang.org/issues/86782013-07-24T14:47:22Znaruse (Yui NARUSE)naruse@airemix.jp
<p>Legacy Ruby 1.8 could regexp match with broken strings.<br>
People can find characters from binary data on the age.</p>
<p>After Ruby 1.9, Ruby raises Exception if it does regexp match with broken strings.<br>
So it became hard to work with character-wise regexp matching with binary data.</p>
<p>Following patch allows it with the constant Regexp::LOOSEENCODING.</p>
<p>commit eb0111ff7ae3f563ce201c4a5f724f121336d42d<br>
Author: NARUSE, Yui <a href="mailto:naruse@ruby-lang.org" class="email">naruse@ruby-lang.org</a><br>
Date: Mon Jul 22 05:37:44 2013 +0900</p>
<pre><code>* Regexp
* New constant:
* Regexp::ENCODINGLOOSE: declare execute matching even if the target string
is invalid byte sequence. [experimental]
</code></pre>
<p>diff --git a/NEWS b/NEWS<br>
index f5fe388..ade0b03 100644<br>
--- a/NEWS<br>
+++ b/NEWS<br>
@@ -35,6 +35,11 @@ with all sufficient information, see the ChangeLog file.</p>
<ul>
<li>misc
<ul>
<li>Mutex#owned? is no longer experimental.</li>
</ul>
</li>
</ul>
<p>+* Regexp</p>
<ul>
<li>
<ul>
<li>New constant:</li>
</ul>
</li>
<li>
<ul>
<li>Regexp::ENCODINGLOOSE: declare execute matching even if the target string</li>
</ul>
</li>
<li>
<pre><code> is invalid byte sequence. [experimental]
</code></pre>
</li>
<li>
</ul>
<ul>
<li>String
<ul>
<li>New methods:
<ul>
<li>String#scrub and String#scrub! verify and fix invalid byte sequence.<br>
diff --git a/re.c b/re.c<br>
index e5cc79d..230a2e0 100644<br>
--- a/re.c<br>
+++ b/re.c<br>
@@ -256,6 +256,7 @@ rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>#define REG_LITERAL FL_USER5<br>
#define REG_ENCODING_NONE FL_USER6<br>
+#define REG_ENCODING_LOOSE FL_USER7</p>
<p>#define KCODE_FIXED FL_USER4</p>
<p>@@ -263,6 +264,7 @@ rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)<br>
(ONIG_OPTION_IGNORECASE|ONIG_OPTION_MULTILINE|ONIG_OPTION_EXTEND)<br>
#define ARG_ENCODING_FIXED 16<br>
#define ARG_ENCODING_NONE 32<br>
+#define ARG_ENCODING_LOOSE 64</p>
<p>static int<br>
char_to_option(int c)<br>
@@ -1251,7 +1253,8 @@ rb_reg_prepare_enc(VALUE re, VALUE str, int warn)<br>
{<br>
rb_encoding *enc = 0;</p>
<ul>
<li>if (rb_enc_str_coderange(str) == ENC_CODERANGE_BROKEN) {</li>
</ul>
<ul>
<li>if (!(RBASIC(re)->flags & REG_ENCODING_LOOSE) &&</li>
<li>
<pre><code> rb_enc_str_coderange(str) == ENC_CODERANGE_BROKEN) {
rb_raise(rb_eArgError,
"invalid byte sequence in %s",
rb_enc_name(rb_enc_get(str)));
</code></pre>
</li>
</ul>
<p>@@ -2433,6 +2436,9 @@ rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc,<br>
if (options & ARG_ENCODING_NONE) {<br>
re->basic.flags |= REG_ENCODING_NONE;<br>
}</p>
<ul>
<li>
<p>if (options & ARG_ENCODING_LOOSE) {</p>
</li>
<li>
<pre><code> re->basic.flags |= REG_ENCODING_LOOSE;
</code></pre>
</li>
<li>
<p>}</p>
<p>re->ptr = make_regexp(RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,<br>
options & ARG_REG_OPTION_MASK, err,<br>
@@ -3091,6 +3097,7 @@ rb_reg_options(VALUE re)<br>
options = RREGEXP(re)->ptr->options & ARG_REG_OPTION_MASK;<br>
if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;<br>
if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;</p>
</li>
<li>
<p>if (RBASIC(re)->flags & REG_ENCODING_LOOSE) options |= ARG_ENCODING_LOOSE;<br>
return options;<br>
}</p>
</li>
</ul>
<p>@@ -3579,6 +3586,8 @@ Init_Regexp(void)<br>
rb_define_const(rb_cRegexp, "FIXEDENCODING", INT2FIX(ARG_ENCODING_FIXED));<br>
/* see Regexp.options and Regexp.new */<br>
rb_define_const(rb_cRegexp, "NOENCODING", INT2FIX(ARG_ENCODING_NONE));</p>
<ul>
<li>
<p>/* see Regexp.options and Regexp.new */</p>
</li>
<li>
<p>rb_define_const(rb_cRegexp, "LOOSEENCODING", INT2FIX(ARG_ENCODING_LOOSE));</p>
<p>rb_global_variable(&reg_cache);</p>
</li>
</ul>
<p>diff --git a/string.c b/string.c<br>
index 1d784e3..caf0baf 100644<br>
--- a/string.c<br>
+++ b/string.c<br>
@@ -3970,7 +3970,7 @@ str_gsub(int argc, VALUE *argv, VALUE str, int bang)<br>
cp = sp;<br>
str_enc = STR_ENC_GET(str);<br>
rb_enc_associate(dest, str_enc);</p>
<ul>
<li>ENC_CODERANGE_SET(dest, rb_enc_asciicompat(str_enc) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID);</li>
</ul>
<ul>
<li>
<p>/<em>ENC_CODERANGE_SET(dest, rb_enc_asciicompat(str_enc) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID);</em>/</p>
<p>do {<br>
n++;<br>
diff --git a/test/ruby/test_regexp.rb b/test/ruby/test_regexp.rb<br>
index 11e86ec..b8f6897 100644<br>
--- a/test/ruby/test_regexp.rb<br>
+++ b/test/ruby/test_regexp.rb<br>
@@ -8,6 +8,10 @@ class TestRegexp < Test::Unit::TestCase<br>
$VERBOSE = nil<br>
end</p>
</li>
<li>
<p>def u(str)</p>
</li>
<li>
<p>str.dup.force_encoding(Encoding::UTF_8)</p>
</li>
<li>
<p>end</p>
</li>
<li>
<p>def teardown<br>
$VERBOSE = @verbose<br>
end<br>
@@ -958,6 +962,17 @@ class TestRegexp < Test::Unit::TestCase<br>
}<br>
end</p>
</li>
<li>
<p>def test_encoding_loose</p>
</li>
<li>
<p>str = u("\x80\xE3\x81\x82\x81")</p>
</li>
<li>
<p>assert_equal(0, Regexp.new(".", Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>assert_equal(1, Regexp.new(u('\p{Any}'), Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>assert_equal(1, Regexp.new("\u3042", Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>assert_equal(1, Regexp.new(u('\p{Hiragana}'), Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>assert_equal(0, Regexp.new(u('\A.\p{Hiragana}.\z'), Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>str = u("\xf1\x80\xE3\x81\x82\x81")</p>
</li>
<li>
<p>assert_equal(0, Regexp.new(u('\A..\p{Hiragana}.\z'), Regexp::LOOSEENCODING) =~ str)</p>
</li>
<li>
<p>end</p>
</li>
<li>
<a name="This-assertion-is-for-porting-x2-tests-in-testpypy-of-Onigmo"></a>
<h1 >This assertion is for porting x2() tests in testpy.py of Onigmo.<a href="#This-assertion-is-for-porting-x2-tests-in-testpypy-of-Onigmo" class="wiki-anchor">¶</a></h1>
<p>def assert_match_at(re, str, positions, msg = nil)<br>
re = Regexp.new(re) unless re.is_a?(Regexp)</p>
</li>
</ul> 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 #8536 (Assigned): Implement is_numeric? family of methodshttps://bugs.ruby-lang.org/issues/85362013-06-17T12:31:08Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
I think Ruby is in dire need of a convenient method for determining whether a string can be safely converted to a number. It's a trivial problem, but with no trivial solution. The most common methods include using regex, or trying to convert the value to the desired type, rescuring any exceptions that are raised. These are not desirable by any means.</p>
<p>I propose a number of new methods be added, either to each of the number classes such as (({Integer.is_integer?})) and (({Numeric.is_numeric?})), to a single parent such as Numeric. For convenience, corresponding methods may also be added to the String class. The methods I propose are...</p>
<ul>
<li>is_numeric?</li>
<li>is_integer?</li>
<li>is_float?</li>
<li>is_rationale?</li>
</ul>
<p>With the exception of numeric, if each of the other methods return true, that value should be safe to use with the corresponding (({Integer("5")})) style methods, and (({to_i})) methods. These boolean methods should behave like the (({Integer("5")})), in that they should disregard/strip whitespace for example.</p>
<p>I think it'd make a nice feature enhancement to Ruby 2.1.<br>
=end</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 #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 #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 #8042 (Assigned): Add Addrinfo#socket to create a socket that is not connec...https://bugs.ruby-lang.org/issues/80422013-03-08T08:35:01Zdrbrain (Eric Hodel)drbrain@segment7.net
<p>This adds a socket method to Addrinfo to get a socket that has not been bound or connected to any address for connectionless operation.</p> Ruby master - Feature #8016 (Assigned): Alias __FILE__ and __LINE__ as methodshttps://bugs.ruby-lang.org/issues/80162013-03-05T12:16:30Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
All of the previous issues discussing the new (({Kernel#<strong>dir</strong>})) method (<a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: Kernel#__dir__ (Closed)" href="https://bugs.ruby-lang.org/issues/1961">#1961</a>, <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: __DIR__ revisted (Closed)" href="https://bugs.ruby-lang.org/issues/3346">#3346</a>, <a class="issue tracker-1 status-6 priority-4 priority-default closed" title="Bug: Why __dir__, not __DIR__ (Rejected)" href="https://bugs.ruby-lang.org/issues/7975">#7975</a>), never came to any conclusion regarding the naming inconsistency between the likes of (({<strong>dir</strong>})) and (({<strong>method</strong>})), and the keywords (({<strong>FILE</strong>})) and (({<strong>LINE</strong>})).</p>
<p>Should we not add (({<strong>file</strong>})) and (({<strong>line</strong>})) as methods also, and perhaps deprecate the keywords (({<strong>FILE</strong>})) and (({<strong>LINE</strong>})). This would keep it consistant with all the other double-underscore methods. To most developers who perhaps do not know Ruby as intricately as most of the people on this issue tracker, the inconsistency between (({<strong>dir</strong>})) and (({<strong>FILE</strong>})) is not just confusing by name, but the fact that one is a method and one isn't, is doubly confusing. Definitely not principle of least surprise.</p>
<p>This needs to be addressed in my opinion, either through deprecation of (({<strong>FILE</strong>})) and (({<strong>LINE</strong>})), or by keeping those keywords and simply creating Kernel method equivalents for the sake of a consistant API.</p>
<p>While on the topic, someone also suggested in one of those previous issues, to give (({<strong>dir</strong>})) an optional join argument, so you could do something like this:</p>
<pre><code>__dir__('somefile.txt') # => /Users/admin/somefile.txt
</code></pre>
<p>I'd predict that at least 90% of use cases for (({<strong>dir</strong>})) will involve joining it to another path or filename. I can't see any harm in adding this. The naming inconstancies are my main concern however. This would just be a nice bonus that takes advantage of the fact that (({<strong>dir</strong>})) is a method rather than a keyword.<br>
=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 #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 #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 #7739 (Assigned): Define Hash#| as Hash#reverse_merge in Railshttps://bugs.ruby-lang.org/issues/77392013-01-24T21:57:20Zalexeymuranov (Alexey Muranov)
<p>=begin<br>
I suggest for to define (({Hash#|})) as (({Hash#reverse_merge})) in ((<em>Rails</em>)), in my opinion this would correspond nicely to (({Set#|})), to the logical (({#||})) and to the bitwise (({#|})):</p>
<p>{ :a => 1, :b => 2 } | { :b => 1, :c => 2 } # => { :a => 1, :b => 1, :c => 2 }<br>
=end</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 #7580 (Assigned): Range translationhttps://bugs.ruby-lang.org/issues/75802012-12-17T14:43:24ZAnonymous
<p>=begin<br>
I would like to propose the (({#+})) and (({#-})) methods on (({Range})).</p>
<p>These would be useful for translating ranges - for example, given a range where the endpoints are 1-indexed, the range could be translated by 1 in the negative direction to use in (({Array#[]})).</p>
<p>Instead of doing a syntactically-bulky manual translation like so:</p>
<p>ary[(range.begin - 1)..(range.end - 1)]</p>
<p>(({Range#-})) could be used instead:</p>
<p>ary[range - 1]</p>
<p>The translation methods would not handle certain endpoint types specially, they would just pass the call on.</p>
<p>Here's an example implementation in Ruby:</p>
<p>class Range<br>
def +(other)<br>
Range.new(self.begin + other, self.end + other, exclude_end?)<br>
end</p>
<pre><code>def -(other)
Range.new(self.begin - other, self.end - other, exclude_end?)
end
</code></pre>
<p>end</p>
<p>=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 #7503 (Assigned): make timeout.rb async-interrupt safe by defaulthttps://bugs.ruby-lang.org/issues/75032012-12-03T22:33:41Zkosaki (Motohiro KOSAKI)kosaki.motohiro@gmail.com
<p>Hi</p>
<p>Again and again we discussed, current timeout.rb is very dangerous because ExitException interrupt argument code and unwind call stack immediately.<br>
It may prevent to run ensure block and makes resource leak.</p>
<p>I proposed change default to interrupted only on blocking point.</p>
<p>patch is here.<br>
<a href="https://gist.github.com/4195015" class="external">https://gist.github.com/4195015</a></p>
<p>I also propse to add 'immediate' optional argument because it may help to make a workaround timeout.rb + zero blocking point corner case.</p>
<p>What do you think?</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 #7436 (Assigned): Allow for a "granularity" flag for backtrace_locationshttps://bugs.ruby-lang.org/issues/74362012-11-26T07:06:40Zsam.saffron (Sam Saffron)sam.saffron@gmail.com
<p>related to <a href="http://bugs.ruby-lang.org/issues/7051" class="external">http://bugs.ruby-lang.org/issues/7051</a></p>
<p>Sometimes one need less information (or more information) associated with backtraces.</p>
<p>It would be nice if one could send in a separate flag informing the VM about the granularity of information required, eg:</p>
<p>caller_locations(0,-current_depth, BacktraceInfo::Label & BacktraceInfo::Lineno)</p>
<p>This allows for one to take quicker backtraces if they need less information, additionally BacktraceInfo::Bindings and BacktraceInfo::Klass could be added which allow you to gather more information for heavy profiling / diagnostics.</p> 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 #7349 (Assigned): Struct#inspect needs more meaningful outputhttps://bugs.ruby-lang.org/issues/73492012-11-14T11:32:05Zpostmodern (Hal Brodigan)postmodern.mod3@gmail.com
<p>When inheriting directly from Struct.new, Class#ancestors shows a meaningless anonymous Class:</p>
<pre><code>class Point < Struct.new(:x, :y)
def distance
((x ** 2) + (y ** 2)) ** 0.5
end
end
Point.ancestors
# => [Point, #<Class:0x007fe204a1a228>, Struct, Enumerable, Object, Kernel, BasicObject]
</code></pre>
<p>Perhaps, the anonymous Class could list the Struct's fields?</p>
<pre><code>#<Class:x, y>
</code></pre> Ruby master - Feature #7314 (Assigned): Convert Proc to Lambda doesn't work in MRIhttps://bugs.ruby-lang.org/issues/73142012-11-09T01:30:19Zschneems (Richard Schneeman)
<p>I have code where I need to convert a proc to a lambda (i need to be able to return out of the block). I would expect that passing a proc into a lambda to return a lambda. When I run this code on MRI i do not get the result I would expect</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">my_proc</span> <span class="o">=</span> <span class="nb">proc</span> <span class="p">{</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">}</span>
<span class="n">my_lambda</span> <span class="o">=</span> <span class="nb">lambda</span> <span class="o">&</span><span class="n">my_proc</span>
<span class="n">my_lambda</span><span class="p">.</span><span class="nf">lambda?</span>
</code></pre>
<p>The result is <code>false</code> but I would expect it to be <code>true</code></p>
<p>There is currently a way to turn a proc into a lambda in MRI like this:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">def</span> <span class="nf">convert_to_lambda</span> <span class="o">&</span><span class="n">block</span>
<span class="n">obj</span> <span class="o">=</span> <span class="no">Object</span><span class="p">.</span><span class="nf">new</span>
<span class="n">obj</span><span class="p">.</span><span class="nf">define_singleton_method</span><span class="p">(</span><span class="ss">:_</span><span class="p">,</span> <span class="o">&</span><span class="n">block</span><span class="p">)</span>
<span class="k">return</span> <span class="n">obj</span><span class="p">.</span><span class="nf">method</span><span class="p">(</span><span class="ss">:_</span><span class="p">).</span><span class="nf">to_proc</span>
<span class="k">end</span>
</code></pre>
<p>But this feels like a hack, and is not supported across other implementations. I would expect that passing a proc into a lambda to return a lambda, I believe it is a bug.</p> Ruby master - Feature #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 #7132 (Assigned): Alternation between named / ordered method arguments and ...https://bugs.ruby-lang.org/issues/71322012-10-09T21:17:44ZAnonymous
<p>=begin<br>
Hi everyone. I am using Ruby for >1 year and I would like to share with you my dreams regarding the named method arguments planned for 2.0. Let us imagine a class Thief with 3 properties (name, hit_points and dexterity), which has constructor #new_thief:</p>
<pre><code>new_thief name: "John Fingers", hit_points: 14, dexterity: 15
</code></pre>
<p>I dream about this constructor accepting alternative syntax:</p>
<pre><code>new_thief "John Fingers", hit_points: 14, dexterity: 15
</code></pre>
<p>and accepting synonyms (aliases) :hp for :hit_points and :dex for dexterity:</p>
<pre><code>new_thief "John Fingers", hp: 14, dex: 15
</code></pre>
<p>To explain my motivation, I am creating a DSL in biology. I am facing the challenge of explaining to my colleagues why is it better than their current Java app. Biologists love synonyms, and I'd like the users calling constructors for biological objects to have freedom to use the synonym they like. Of course, I can already achieve it in 1.9.3:</p>
<pre><code>def new_thief *args
oo = args.extract_options!
raise ArgumentError if args[0] and oo[:name] and args[0] != oo[:name]
name = args[0] || oo[:name] || "John Doe"
raise ArgumentError if oo[:hp] and oo[:hit_points] and oo[:hp] != oo[:hit_points]
hp = oo[:hp] || oo[:hit_points] || 9
raise ArgumentError if oo[:dex] and oo[:dexterity] and oo[:dex] != oo[:dexterity]
dex = oo[:dex] || oo[:dexterity] || 11
Thief.new( name: name, hit_points: hp, dexterity: dex )
end
</code></pre>
<p>But I find myself doing this over and over, and even if I write a library to make it easier, it's still too cumbersome.</p>
<p>Proposal no. 1: I propose that alternation between named / ordered arguments and aliases (synonyms) for named method arguments be catered for already by core syntax.</p>
<p>Proposal no. 2: I propose that the syntax for this be as follows:</p>
<pre><code>def new_thief( name=**:name="John Doe", hp: **:hit_points=14, dex: **:dexterity=15 )
Thief.new name: name, hit_points: hp, strength: str, dexterity: dex
end
</code></pre>
<p>where expressions **:arg_name would refer to the named argument :arg_name.</p>
<p>Please judge the two proposals independently. I really dream about having the alternation between named / ordered arguments and aliases for named arguments in Ruby 2.0. But I feel less sure that the syntax **:arg_name that I am proposing is the best possible syntax for this. Mind me, I don't think it is bad, I am just not sure it is <em>best</em>.</p>
<p>PS: Please forgive me suggesting such a complicated feature, while being unable to write a single line in C.<br>
=end</p> Ruby master - Feature #7121 (Assigned): Extending the use of `require'https://bugs.ruby-lang.org/issues/71212012-10-09T10:09:29Zmjones (Morgan Jones)integ3rs@gmail.com
<p>=begin<br>
I was playing with Ruby tonight and thought up an interesting idea to make (({require})) a bit better, so you can load multiple files sequentially using one method call.</p>
<p>Currently, (({require})) supports one argument, and throws a (({TypeError})) if you pass an array:</p>
<p>irb(main):001:0> require %w(json yaml)<br>
TypeError: can't convert Array into String</p>
<p>However, there's a way to patch Kernel that makes it respond to multiple objects passed in an (({Array})).</p>
<p>module Kernel<br>
@@require = method :require</p>
<p>def require *args<br>
args.flatten!<br>
args.collect! do |a|<br>
raise ArgumentError.new "arguments to `require' must be strings or symbols" unless a.is_a?(String) || a.is_a?(Symbol)<br>
@@require.call a.to_s<br>
end</p>
<pre><code> args.length == 1 ? args.first : args
</code></pre>
<p>end<br>
end</p>
<p>The new behavior doesn't actually require the modification of any code that calls (({require})) (pretty much anything, really), and new code can take advantage of the new functionality instantly.</p>
<p>irb> require %w(json yaml)<br>
=> [true, false]<br>
irb> require :pp<br>
=> false<br>
irb> require 'rails'<br>
=> true<br>
irb> require %w(json yaml), :pp, 'rails'<br>
=> [true, false, false, true]<br>
=end</p>
<p>Thanks for considering this.</p> Ruby master - Feature #7087 (Assigned): ::ConditionVariable#wait does not work with Monitor becau...https://bugs.ruby-lang.org/issues/70872012-09-30T00:19:32Zrklemme (Robert Klemme)shortcutter@googlemail.com
<p>See program attached to bug <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: ConditionVariable#wait has meaningless return value (Assigned)" href="https://bugs.ruby-lang.org/issues/7086">#7086</a>: timeout_4 always throws:</p>
<p>ERROR: method "timeout_4": #<NoMethodError: private method `sleep' called for #<a href="Monitor:0x87e49f8" class="external">Monitor:0x87e49f8</a>></p>
<p>$ irb19 -r monitor<br>
irb(main):001:0> Monitor.new.method(:sleep)<br>
=> #<Method: Monitor(Kernel)#sleep><br>
irb(main):002:0> Monitor.instance_methods.grep /sleep/<br>
=> []</p> Ruby master - Feature #6842 (Assigned): Add Optional Arguments to String#striphttps://bugs.ruby-lang.org/issues/68422012-08-07T20:24:20Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
One of the very few things I miss from the ol' php days many years ago, was the ability to easily strip arbitrary characters from the ends of string using trim(). Typically, this is whitespace characters, and #strip currently fulfils that use case, but there are also instances where it'd be nice to be able to strip any range of characters from the ends of a string. It goes well with Array#join as often when joining strings with a delimiter, you want to make sure those strings don't already begin or end with that character.</p>
<p>For a full-featured #strip, I'd like to see it have the option of accepting both an Array or String. If a string is provided, each character in that string will be stripped. If an array of strings is given, each element of the array is stripped from the ends of the string - this allows for multi-character delimiters for example. Of course you could go really nuts and supports regex as well (or instead of arrays). To demonstrate the difference...</p>
<pre><code>"<b>bold text</b>".strip("</b>") #=> "old text"
"<b>bold text</b>".strip(["<b>", "</b>"]) #=> "bold text"
"<em><b>bold text</b></em>".strip(["<b>", "</b>", "<em>", "</em>"]) #=> "bold text"
"<em><b>bold text</b></em>".strip(/<\/?.+?>/) #=> "bold text"
</code></pre>
<p>A simple real-world example; this is actually what I was wanting to do right before I came here to raise this feature request, but there's been all kinds of other use cases I've hit in the past:</p>
<pre><code>['some', '/chunked', 'path/'].map{ |v| v.strip('/') }.join('/') #=> "some/chunked/path"
</code></pre>
<p>File#join does something similar, but when you need control over the joining character, this is the way you'd do it.</p>
<p>I've lost count of how many times I've wanted this in Ruby, and there's really no nice workaround. Here's an example on StackOverflow of someone asking how to achieve this stripping behaviour in ruby: <a href="http://stackoverflow.com/questions/3453262/how-to-strip-leading-and-trailing-quote-from-string-in-ruby" class="external">http://stackoverflow.com/questions/3453262/how-to-strip-leading-and-trailing-quote-from-string-in-ruby</a></p>
<p>Obviously, you'd do the same for #lstrip and #rstrip, and all the mutable variants (#strip!, #lstrip!, #rstrip!). Looking forward to others thoughts on this one.<br>
=end</p> Ruby master - Feature #6817 (Open): Partial applicationhttps://bugs.ruby-lang.org/issues/68172012-07-31T15:38:35Zcitizen428 (Michael Kohl)citizen428@gmail.com
<p>I know that what I propose here is a significant change to Ruby, but it's part of my ongoing quest to get some more functional programming features into Ruby (see also <a class="issue tracker-2 status-2 priority-4 priority-default" title="Feature: Array#zip_with (Assigned)" href="https://bugs.ruby-lang.org/issues/4539">#4539</a> and <a class="issue tracker-2 status-5 priority-4 priority-default closed" title="Feature: public #self (Closed)" href="https://bugs.ruby-lang.org/issues/6373">#6373</a>).</p>
<p>I was wondering if it would make sense to maybe introduce partial application to Ruby? So that instead of</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">2</span> <span class="p">}</span>
</code></pre>
<p>or the somewhat unwieldy</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="mi">2</span><span class="p">.</span><span class="nf">method</span><span class="p">(:</span><span class="o">+</span><span class="p">))</span>
</code></pre>
<p>one could just write</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">3</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&</span><span class="mi">2</span><span class="p">.</span><span class="nf">+</span><span class="p">)</span>
</code></pre>
<p>which I think has a quite rubyish feel to it. I have a POC implementation in Ruby (I tried it with various <code>Fixnum</code> methods) over at <a href="http://citizen428.net/blog/2012/07/30/ruby-left-section-for-infix-operators" class="external">my blog</a>, but that was just a quick hack and obviously I don't want to monkey-patch every method with arity 1, but it was a nice way of exploring possible syntax.</p> Ruby master - Feature #6811 (Assigned): File, Dir and FileUtils should have bang-versions of sing...https://bugs.ruby-lang.org/issues/68112012-07-29T20:34:08Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>I found that often write<br>
Dir.mkdir(folder) unless Dir.exist? folder<br>
and similar code for rm, rm_rf and so on<br>
We can simply make bang-versions like<br>
def Dir.mkdir!(folder, permissions=0744)<br>
Dir.mkdir(folder, permissions) unless Dir.exist? folder</p>
<a name="or-another-alternative-Dirmkdirfolder-permissions-rescue-false"></a>
<h1 >or another alternative Dir.mkdir(folder, permissions) rescue false<a href="#or-another-alternative-Dirmkdirfolder-permissions-rescue-false" class="wiki-anchor">¶</a></h1>
<p>end</p> Ruby master - Feature #6802 (Assigned): String#scan should have equivalent yielding MatchDatahttps://bugs.ruby-lang.org/issues/68022012-07-27T16:17:42Zprijutme4ty (Ilya Vorontsov)prijutme4ty@gmail.com
<p>Ruby should have method to obtain not an array of arrays but of MatchData objects. It can help in obtaining named groups:</p>
<p>pattern = /x: (?\d+) y:(?\d+)/<br>
polygon = []<br>
text.scan_for_pattern(pattern){|m| polygon << Point.new(m[:x], m[:y]) }</p>
<p>Not to break existing code we need unique name. Ideas? May be #each_match</p> Ruby master - Feature #6671 (Assigned): File.split_all and File.split_roothttps://bugs.ruby-lang.org/issues/66712012-06-30T04:28:57Ztrans (Thomas Sawyer)
<p>=begin<br>
Is there a method for this already?</p>
<p>File.split_all('a/b/c') #=> ['a','b','c']</p>
<p>If not I propose it be added. I've had need of such more than a few times.</p>
<p>It's too bad that File.split can't do this, as it would make more sense. And the current method be called <code>split_base</code>.</p>
<p>In addition <code>split_root</code> would be helpful.</p>
<p>root, path = File.split_all('a/b/c')<br>
root #=> 'a'<br>
path #=> 'b/c'<br>
=end</p> Ruby master - Feature #6648 (Assigned): Provide a standard API for retrieving all command-line fl...https://bugs.ruby-lang.org/issues/66482012-06-26T07:56:37Zheadius (Charles Nutter)headius@headius.com
<p>=begin<br>
Currently there are no standard mechanisms to get the flags passed to the currently running Ruby implementation. The available mechanisms are not ideal:</p>
<ul>
<li>Scanning globals and hoping they have not been tweaked to new settings</li>
<li>Using external wrappers to launch Ruby</li>
<li>???</li>
</ul>
<p>Inability to get the full set of command-line flags, including flags passed to the VM itself (and probably VM-specific) makes it impossible to launch subprocess Ruby instances with the same settings.</p>
<p>A real world example of this is "((%bundle exec%))" when called with a command line that sets various flags, a la ((%jruby -Xsome.vm.setting --1.9 -S bundle exec%)). None of these flags can propagate to the subprocess, so odd behaviors result. The only option is to put the flags into an env var (((|JRUBY_OPTS|)) or ((|RUBYOPT|))) but this breaks the flow of calling a simple command line.</p>
<p>JRuby provides mechanisms to get all its command line options, but they require calling Java APIs from Ruby's API set. Rubinius provides its own API for accessing comand-line options, but I do not know if it includes VM-level flags as well as standard Ruby flags.</p>
<p>I know there is a (({RubyVM})) namespace in the 2.0 line. If that namespace is intended to be general-purpose for VM-level features, it would be a good host for this API. Something like...</p>
<p>class << RubyVM<br>
def vm_args; end # returns array of command line args <em>not</em> passed to the target script</p>
<pre><code>def script; end # returns the script being executed...though this overlaps with $0
def script_args; end # returns args passed to the script...though this overlaps with ARGV, but that is perhaps warranted since ARGV can be modified (i.e. you probably want the original args)
</code></pre>
<p>end<br>
=end</p> Ruby master - Feature #6641 (Open): Hash.auto constructorhttps://bugs.ruby-lang.org/issues/66412012-06-25T09:34:06Ztrans (Thomas Sawyer)
<p>=begin<br>
It is not uncommon to need a Hash following the pattern:</p>
<p>Hash.new{ |h,k| h[k]={} }</p>
<p>Another common example:</p>
<p>Hash.new{ |h,k| h[k]=[] }</p>
<p>This is common enough that it would very nice if we could have a more concise form, e.g.</p>
<p>Hash.auto{ {} }</p>
<p>Or for the second example:</p>
<p>Hash.auto{ [] }</p>
<p>Pure Ruby implementation is pretty simple:</p>
<p>def Hash.auto<br>
Hash.new{ |h,k| h[k] = yield }<br>
end</p>
<p>I think it would be nice to have in Core.</p>
<p>This is secondary, but it just occurred to me. Could there even be a literal notation for the above? Something like:</p>
<p>{}([])</p>
<p>?<br>
=end</p> Ruby master - Feature #6611 (Assigned): Comments requested on implementation of set_parse_funchttps://bugs.ruby-lang.org/issues/66112012-06-20T07:46:26Zcjheath (Clifford Heath)clifford.heath@gmail.com
<p>Folk,</p>
<p>I've implemented Twister, a new mutation testing tool to replace Heckle.<br>
It relies on a new hook into the Ruby parser, in order to modify what the<br>
parser thinks it has seen.</p>
<p>Although I have written C extensions before, there are some aspects of<br>
the Ruby core which I'm unfamiliar with and as a result don't know the right<br>
way to handle. I'd like your comments, suggestions and improvements<br>
please.</p>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db</a></p>
<p>In particular, I'd like to know the following:</p>
<ol>
<li>Do you prefer that I move the literal strings (which occur once each) to #defined?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R1003" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R1003</a></p>
<ol start="2">
<li>Will this line of code mess up the GC, and how should I fix that?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R3853" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R3853</a></p>
<ol start="3">
<li>The set_parse_func is extern though it should be static, but I need to move<br>
the rb_define_global_function out of thread.c. Can someone please tell me where I should<br>
move it to, since there is no Init_Parser?</li>
</ol>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R9029" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L1R9029</a></p>
<p><a href="https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L3R4705" class="external">https://github.com/cjheath/ruby/commit/ea99527feaf7dd06b3e8433ec640238441b188db#L3R4705</a></p>
<ol start="4">
<li>I think I should change set_parse_func to accept a flags argument and a block,<br>
instead of assuming all flags, and taking a Proc. What are the downsides of using a<br>
block instead of a Proc (does this reduce the number of Bindings that get created)?<br>
How do I change set_parse_func to use a block?</li>
</ol>
<p>The initial implementation of Twister is an extension to RSpec which adds the option<br>
"--twist file-or-dir". It's still a bit rough - it needs to change the reporting on the twisted<br>
runs that follow the first (untwisted) run - but it does prove then concept.</p>
<p>Clifford Heath, Data Constellation, <a href="http://dataconstellation.com" class="external">http://dataconstellation.com</a><br>
Agile Information Management and Design.</p> Ruby master - Feature #6445 (Assigned): request for default length/position on string indexhttps://bugs.ruby-lang.org/issues/64452012-05-17T13:02:30Zbotp (bot pena)botpena@gmail.com
<p>would be nice if ruby has default for "rest or up to end of string"</p>
<p>eg</p>
<p>"hello"[2,] => should default to "hello"[2..-1]<br>
or<br>
"hello"[2..] => should default to "hello"[2..-1]</p> Ruby master - Feature #6413 (Assigned): Make Dir.entries default to Dir.entries(Dir.pwd)https://bugs.ruby-lang.org/issues/64132012-05-08T22:12:34Zshevegen (Robert A. Heiler)shevegen@gmail.com
<p>Is there a reason why Dir.entries requires one argument?</p>
<p>I think it would be easier and more convenient for the userruby if it would default to the current directory. Like so:</p>
<p>Dir.entries(i = Dir.pwd)</p>
<p>Or is there a reason why this is not done?</p> Ruby master - Feature #6376 (Assigned): Feature lookup and checking if feature is loadedhttps://bugs.ruby-lang.org/issues/63762012-04-29T07:03:40Ztrans (Thomas Sawyer)
<p>$LOADED_FEATURES is useful to know what "files" have been loaded. But it doesn't really tell us what "features" have been loaded. If there where were a way to look-up a load path, without actually loading it then it would be possible to compare that to $LOADED_FEATURES and thus know. e.g.</p>
<pre><code>require 'ostruct'
$LOADED_FEATURES #=> [..., "/home/trans/.local/lib/ry/rubies/1.9.3-p125/lib/ruby/1.9.1/ostruct.rb"]
path = require_path('ostruct') #=> "/home/trans/.local/lib/ry/rubies/1.9.3-p125/lib/ruby/1.9.1/ostruct.rb"
$LOADED_FEATURES.include?(path)
</code></pre>
<p>Of course, it would be nice to also have:</p>
<pre><code>required?('ostruct') #=> true
</code></pre>
<p>These methods could be class methods of special module, if it's important to keep the Kernel more tidy, e.g. <code>Ruby.required?('ostruct')</code>.</p>
<p>I am currently working on a project where I need this (and have a couple of other projects that could use it too) and I've had to implement the whole thing from scratch, which isn't simple, nor fast, nor am I 100% confident that it specs exactly to Ruby's own lookup procedure. So it would be much better if Ruby would expose its lookup functionality.</p> Ruby master - Feature #6354 (Assigned): Remove escape (break/return/redo/next support) from class...https://bugs.ruby-lang.org/issues/63542012-04-25T12:12:17Zko1 (Koichi Sasada)
<p>Let's remove global escape (break/return/redo/next support) from class/module scope.</p>
<p>Yes, it introduces incompatibility. However, anyone use it?<br>
I think the following examples are evil (difficult to understand).</p>
<a name="examples"></a>
<h1 >examples:<a href="#examples" class="wiki-anchor">¶</a></h1>
<p>1.times{<br>
class C<br>
break # break from 1.times<br>
end<br>
}</p>
<p>1.times{<br>
class C<br>
module M<br>
break # break from 1.times<br>
end<br>
end<br>
}</p>
<p>3.times{|n|<br>
p n # repeat print 0<br>
class C<br>
redo<br>
end<br>
}</p>
<p>->{<br>
class C<br>
return return from outer lambda block<br>
end<br>
}.call</p>
<p>->{<br>
proc{<br>
class C<br>
return # return from outer lambda (not proc) block<br>
end<br>
}.call<br>
}.call</p>
<p>etc, etc.</p> Ruby master - Feature #6293 (Assigned): new queue / blocking queueshttps://bugs.ruby-lang.org/issues/62932012-04-14T08:28:58Ztenderlovemaking (Aaron Patterson)tenderlove@ruby-lang.org
<p>Hi,</p>
<p>I'd like to add new Queue objects to ruby. Whenever I use queues, I either use them in a blocking or non-blocking manner only, so I have separated them in to two classes Thread::Queue, and Thread::BlockingQueue.</p>
<p>Other notable differences, these queues:</p>
<ul>
<li>implement <code>poll</code>, which will return a nil if the queue is empty</li>
<li>do not allow <code>nil</code> to be in the queue as it would interfere with <code>poll</code>
</li>
<li>include Enumerable</li>
</ul>
<p>I think these will be a good basis for implementing a Deque, SynchronizedQueue, and PriorityQueue.</p>
<p>I've attached a patch against trunk.</p> Ruby master - Feature #6277 (Assigned): Hash#convert_keyhttps://bugs.ruby-lang.org/issues/62772012-04-11T01:12:20Ztrans (Thomas Sawyer)
<p>=begin<br>
Many times a hash with uniform keys is needed (or is at least preferable) for a particular usecase. To this end I propose ((%Hash#convert_key%)).</p>
<p>h = {}<br>
h.convert_key{ |k| k.to_sym }<br>
h['a'] = 1<br>
h.update('b'=>2)<br>
h #=> {:a=>1, :b=>2}</p>
<p>The idea is similar in concept to ((%#default_proc%)).</p>
<p>Others solutions to fill this need have been tried and used, but almost exclusively are in the form of a new class. Most notable is Rails HashWithIndifferentAccess. But ((%#convert_key%)) has much greater flexibility since keys can be converted to anything.<br>
=end</p> Ruby master - Feature #5970 (Assigned): Add Enumerable#join with same semantics as Array#joinhttps://bugs.ruby-lang.org/issues/59702012-02-05T17:27:39Znow (Nikolai Weibull)now@disu.se
<p>Currently, to join the elements of an Enumerable, you need to call #to_a on the Enumerable and then #join the result. With Enumerable#join one wouldn’t need need to create an intermediate Array.</p> Ruby master - Feature #5945 (Assigned): Add the ability to mark a at_exit as process-local. https://bugs.ruby-lang.org/issues/59452012-01-30T09:59:36Zrobertgleeson (Robert Gleeson)
<p>I'd like to propose a enhancement to <code>at_exit</code>.<br>
It would be nice if you could stop a <code>at_exit</code> handler from running in subprocesses.<br>
You can do this manually with this code:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">parent</span> <span class="o">=</span> <span class="no">Process</span><span class="p">.</span><span class="nf">pid</span>
<span class="nb">at_exit</span> <span class="k">do</span>
<span class="k">if</span> <span class="n">parent</span> <span class="o">==</span> <span class="no">Process</span><span class="p">.</span><span class="nf">pid</span>
<span class="c1"># …</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<p>You can also do it by bypassing handlers:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">at_exit</span> <span class="k">do</span>
<span class="c1"># …</span>
<span class="k">end</span>
<span class="nb">fork</span> <span class="k">do</span>
<span class="nb">exit!</span>
<span class="k">end</span>
</code></pre>
<p>But it would be nice if I could do:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">at_exit</span><span class="p">(</span><span class="kp">false</span><span class="p">)</span> <span class="k">do</span>
<span class="c1"># …</span>
<span class="k">end</span>
</code></pre>
<p>The first approach is kind of ugly, and the second approach isn't sustainable if code outside<br>
your control can <code>fork(…)</code> without calling <code>exit!</code>.</p> Ruby master - Feature #5749 (Assigned): new method String#match_all neededhttps://bugs.ruby-lang.org/issues/57492011-12-12T18:03:57Zyimutang (Joey Zhou)
<p>The String class should contain an instance method 'match_all', which is a mixture of 'match' and 'scan'.</p>
<p>The method 'scan' is not a very powerful tool, its result(the yielding thing) is just a matched string or an array of captured strings.</p>
<p>p 'a1bc2de3f'.scan(/(.)\d(.)/) # [["a", "b"], ["c", "d"], ["e", "f"]]</p>
<p>If the regex argument contains groups, I even cannot get the whole matched string, and no information about the matched offsets.</p>
<p>So, a 'match_all' is very necessary. It scan the string, finding every matched, and yielding <em>MatchData instance</em> to the following block.</p>
<p>Here's a simple implemention in Ruby:</p>
<p>class String<br>
def match_all(re,i=0)<br>
if block_given?<br>
while m = self.match(re,i)<br>
yield m<br>
i = m.end(0)<br>
end<br>
return self<br>
else<br>
ary = []<br>
while m = self.match(re,i)<br>
ary << m<br>
i = m.end(0)<br>
end<br>
return ary<br>
end<br>
end<br>
end</p>
<p>However, it is not efficient in the 'while m = self.match(re,i)' way, because it scan the string again and again. If string is UTF8-encoded and contains out-of-ASCII characters, I'm afraid getting the start index of it is so expensive.</p>
<p>So, I think a built-in 'match_all' method, which behaves just like 'scan' but yield MatchData, is needed.</p>
<p>Please consider it, thank you!</p> Ruby master - Feature #5741 (Assigned): Secure Erasure of Passwordshttps://bugs.ruby-lang.org/issues/57412011-12-11T06:02:13ZMartinBosslet (Martin Bosslet)Martin.Bosslet@gmail.com
<p>In other languages it is considered good practice to securely erase<br>
passwords immediately after they were used. Imagine authentication<br>
in a web app - ultimately a String containing the password arrives<br>
at the server, where it will be processed and compared to some<br>
previously stored value. After this is done, there is no need to<br>
store these password Strings any longer, so they should be<br>
discarded right away (more on why later).</p>
<p>In C, you would simply overwrite the array of bytes with zeroes or<br>
random values. In Java, Strings are immutable, that's why there it<br>
is common practice to use char[] for all things password and overwrite<br>
them when done.</p>
<p>Currently, there is no way in Ruby to overwrite the memory that<br>
was used by a String. String#clear and String#replace both use<br>
str_discard internally, which only frees the underlying pointer<br>
without overwriting it.</p>
<p>The problem with not erasing passwords is this: the contents of the<br>
String stay in memory until they are finally GC'ed. But even then<br>
only the pointer will be freed, leaving the contents mostly intact<br>
until the memory is reclaimed and overwritten later on.</p>
<p>This could be exploited if an attacker had access to the memory of<br>
the server. This could happen in many ways: a core dump after a<br>
crash, access to the host if the server runs in a VM, or even by<br>
deep-freezing the DRAM :) [1]</p>
<p>It could be argued that given the examples above, much more<br>
devastating attacks would be possible since in all of those<br>
cases you more or less have physical access to the machine. But<br>
I would still consider this to be a valid concern, if not only<br>
for the reason of never opening additional attack surfaces if<br>
they can be avoided relatively easily.</p>
<p>I also found [2], which seems to show that Python deals with<br>
similar problems and it also contains more background info.</p>
<p>Eric Hodel and I discussed this yesterday and Eric came up with<br>
a C extension that can be used to illustrate the problem (attached).</p>
<p>If you inspect the resulting core dump, you will find the following:</p>
<ul>
<li>the untouched String remains in memory fully intact</li>
<li>the String#clear'ed String remains to a large extent, typically the<br>
first character is missing - so if you typed "PASSWORD", search for<br>
"ASSWORD" (unintentional pun) instead</li>
<li>The String#clear_secure'ed will have been completely erased, no<br>
traces remain</li>
</ul>
<p>My questions:</p>
<ol>
<li>Would you agree that we need this functionality?</li>
<li>Where would we ideally place it? I'm not sure whether<br>
String is the perfect place, but on the other hand, String<br>
is the only place where we have access to the implementation<br>
details.</li>
<li>Are there better alternative ways how we could achieve this?</li>
</ol>
<p>[1] <a href="http://www.schneier.com/blog/archives/2008/02/cold_boot_attac.html" class="external">http://www.schneier.com/blog/archives/2008/02/cold_boot_attac.html</a><br>
[2] <a href="http://stackoverflow.com/questions/728164/securely-erasing-password-in-memory-python" class="external">http://stackoverflow.com/questions/728164/securely-erasing-password-in-memory-python</a></p> Ruby master - Feature #5643 (Assigned): require/load options and binding optionhttps://bugs.ruby-lang.org/issues/56432011-11-17T07:41:01Ztrans (Thomas Sawyer)
<p>Current Kernel#load is defined as:</p>
<pre><code>load(filename, wrap=false)
</code></pre>
<p>I purpose that it be modified to work as option argument, e.g.</p>
<pre><code>load(filename, :wrap=>true)
</code></pre>
<p>Right off the bat this has better name connascence.</p>
<p>Then support an additional option <code>:binding</code>, such that, given:</p>
<pre><code>$ cat lib/example.rb
def a
1
end
</code></pre>
<p>then</p>
<pre><code>class X
load('example.rb', :binding=>binding)
end
X.new.a #=> 1
</code></pre>
<p>The binding option should also work with #require (which would also support option parameter) differing from #load in the it would only allow the feature to be loaded once per-binding's self regardless of being required again.</p>
<p>This ability would greatly benefit systems that need "plugin" capability. Presently, a great deal of coding has to go into simulating this functionality to create plugin systems, which are often imperfect nor robust.</p> Ruby master - Feature #5582 (Assigned): Allow clone of singleton methods on a BasicObjecthttps://bugs.ruby-lang.org/issues/55822011-11-07T12:34:13Zthinkerbot (Simon Chiang)simon.a.chiang@gmail.com
<p>Currently I do not know of a way to implement something like 'clone' on a BasicObject subclass. This is as close as I've gotten but as you can see the singleton methods are not propagated to the clone.</p>
<pre><code>require 'test/unit'
class Context < BasicObject
def _singleton_class_
class << self
SINGLETON_CLASS = self
def _singleton_class_
SINGLETON_CLASS
end
end
_singleton_class_
end
def _class_
_singleton_class_.superclass
end
def _extend_(mod)
mod.__send__(:extend_object, self)
end
def _initialize_clone_(orig)
# set variables as needed
end
def _clone_
clone = _class_.allocate
clone._initialize_clone_(self)
_singleton_class_.included_modules.each {|mod| clone._extend_ mod }
clone
end
end
class ContextTest < Test::Unit::TestCase
module A
def a
:a
end
end
def test__clone__inherits_modules
context = Context.new
context._extend_ A
clone = context._clone_
assert_equal :a, clone.a
end
def test__clone__inherits_singleton_methods
context = Context.new
def context.a
:a
end
clone = context._clone_
assert_equal :a, clone.a # fails
end
end
</code></pre>
<p>Is there a way to do this that I don't see? If not, then I request that a way be added - perhaps by allowing the singleton_class to be set somehow.</p>
<p>In my case I am using Context as the context for a dsl where methods write to a target (an instance variable). I want to be able to clone a context such that I can have multiple contexts with the same methods, including extensions and singletons, that write to different targets.</p>
<p>Thank you.</p> Ruby master - Feature #5558 (Assigned): String#% strange arity errorshttps://bugs.ruby-lang.org/issues/55582011-11-03T10:25:55Ztrans (Thomas Sawyer)
<p>When the number of arguments do not match the number of % parameters, the String#% method has some odd behavior.</p>
<p>When too many, it seems to work fine, ignoring the extra arguments.</p>
<p>"%s" % [1,2] #=> "1"</p>
<p>But if <code>$DEBUG = true</code>,</p>
<p>"%s" % [1,2] #=> ArgumentError: too many arguments for format string</p>
<p>That doesn't seem right. Is it an error or isn't it?</p>
<p>For too few arguments it is always an error:</p>
<p>"%s" % [] #=> ArgumentError: too few arguments</p>
<p>Personally, I think it should use '' for missing arguments. That would make it more flexible in practice.</p>
<p>I consider the first $DEBUG issue a bug, and the later a feature. But I'll just call it a feature altogether to make things easier.</p> Ruby master - Feature #5445 (Assigned): Need RUBYOPT -r before ARGV -rhttps://bugs.ruby-lang.org/issues/54452011-10-14T00:47:09Ztrans (Thomas Sawyer)
<p>Libraries given by -r options in RUBYOPT should be loaded before ones in direct command line arguments.</p>
<p>I use a custom load system for development that I have been using for years and it works very well for me. But Ruby has some edge cases that prevents it from being feature complete. One of these is the order in which RUBYOPT is applied vs. -r command line option.</p>
<p>My custom loader is too large to include here, so I will simply demonstrate the problem with simple sample code:</p>
<p>$ cat req.rb<br>
p "Custom Require"</p>
<p>module Kernel<br>
alias :require0 :require</p>
<pre><code>def require(*a)
puts "Kernel#require"
p a
require0(*a)
end
class << self
alias :require0 :require
def require(*a)
puts "Kernel.require"
p a
require0(*a)
end
end
</code></pre>
<p>end</p>
<p>If we load this via RUBYOPT, the result is:</p>
<p>$ RUBYOPT=-r./req.rb ruby -rstringio -e0<br>
Custom Require</p>
<p>But if we load via -r the result is:</p>
<p>$ ruby -r./req.rb -rstringio -e0<br>
Custom Require<br>
Kernel#require<br>
["stringio"]</p>
<p>I would ask that the output of both invocations to be identical.</p>
<p>(Note, the -T option should still allow RUBYOPT to be omitted regardless.)</p> Ruby master - Feature #5389 (Assigned): New method Enumerator#iteratehttps://bugs.ruby-lang.org/issues/53892011-10-03T20:25:16Zyimutang (Joey Zhou)
<p>If we want to iterate over the elements of a enumerable object with <em>multiple</em> blocks, we can use the Enumerator class.</p>
<p>A method 'iterate' is required, we can write it in Ruby:</p>
<pre><code>class Enumerator
def iterate
yield_value = self.next
return_value = yield yield_value
self.feed return_value
self
end
end
</code></pre>
<p>Well, here is an example:</p>
<pre><code>array = (1..10).to_a
enum = array.map!
loop do
enum.iterate {|n| n + 10 }
enum.iterate {|n| n * 2 }
enum.iterate {|n| -n }
end
p array # => [11, 4, -3, 14, 10, -6, 17, 16, -9, 20]
</code></pre>
<p>We want to map an array: the 1st element use blk1, the 2nd use blk2, the 3rd use blk3...</p>
<p>I think this Enumerator#iterate method is sometimes useful, so would you please introduce it into the language core?</p> Ruby master - Feature #5129 (Assigned): Create a core class "FileArray" and make "ARGF" its instancehttps://bugs.ruby-lang.org/issues/51292011-08-01T13:57:46Zyimutang (Joey Zhou)
<p>I suggest to create a class "<code>FileArray</code>" whose instance behaves just like <code>ARGF</code> do.<br>
And I think <code>ARGF</code> should be an instance of <code>FileArray</code>. Now when I "<code>p ARGF.class</code>", I get "<code>ARGF.class</code>", so <code>ARGF</code> is an instance of <code>ARGF.class</code>, how meaningless it is.</p>
<p>FileArray methods:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="c1"># create an instance</span>
<span class="n">fa</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'a.txt'</span><span class="p">,</span><span class="s1">'b.txt'</span><span class="p">,</span><span class="s1">'c.txt'</span><span class="p">)</span>
<span class="c1"># take many methods from IO</span>
<span class="c1"># most methods from ARGF should be instance methods of ARGF </span>
<span class="n">fa</span><span class="p">.</span><span class="nf">each</span> <span class="p">{</span><span class="o">|</span><span class="n">line</span><span class="o">|</span> <span class="nb">puts</span> <span class="n">line</span> <span class="p">}</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">realines</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># current file</span>
<span class="c1"># but "argv" not</span>
<span class="nb">p</span> <span class="n">fa</span><span class="p">.</span><span class="nf">file_list</span> <span class="c1"># in ARGF, its ARGF.argv, but #argv is not a proper name for FileArray</span>
<span class="c1"># ARGV array can be modified, adding new file into it, all replace to a new file list.</span>
<span class="c1"># FileArray should add some methods to modify the inner file list.</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">insert</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="s2">"d.txt"</span><span class="p">)</span>
<span class="n">fa</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="s1">'a.txt'</span><span class="p">)</span>
</code></pre>
<p>With <code>FileArray</code>, You can create multiple <code>ARGF</code>-like file arrays simultaneously.</p>
<p>For example, I want to mix two <em>groups</em> of files, not two files:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">a_files</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="o">*</span><span class="no">Dir</span><span class="p">.</span><span class="nf">glob</span><span class="p">(</span><span class="s1">'a*.txt'</span><span class="p">))</span>
<span class="n">b_files</span> <span class="o">=</span> <span class="no">FileArray</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="o">*</span><span class="no">Dir</span><span class="p">.</span><span class="nf">glob</span><span class="p">(</span><span class="s1">'b*.txt'</span><span class="p">))</span>
<span class="n">enum_a</span> <span class="o">=</span> <span class="n">a_files</span><span class="p">.</span><span class="nf">each</span>
<span class="n">enum_b</span> <span class="o">=</span> <span class="n">b_files</span><span class="p">.</span><span class="nf">each</span>
<span class="kp">loop</span> <span class="k">do</span>
<span class="nb">puts</span> <span class="n">enum_a</span><span class="p">.</span><span class="nf">next</span>
<span class="nb">puts</span> <span class="n">enum_b</span><span class="p">.</span><span class="nf">next</span>
<span class="k">end</span>
</code></pre> Ruby master - Feature #5064 (Assigned): HTTP user-agent classhttps://bugs.ruby-lang.org/issues/50642011-07-21T13:10:00Zdrbrain (Eric Hodel)drbrain@segment7.net
<p>Currently there are some problems with Net::HTTP:</p>
<ul>
<li>Too many ways to use (user confusion)</li>
<li>No automatic support for HTTPS (must conditionally set use_ssl)</li>
<li>No automatic support for HTTPS peer verification (must be manually set)</li>
<li>Single-connection oriented</li>
<li>No support for redirect-following</li>
<li>No support for HTTP/1.1 persistent connection retry (RFC 2616 8.1.4)</li>
<li>No automatic support for HTTP proxies</li>
<li>No automatic support for authentication (must be set per-request)</li>
</ul>
<p>Additionally the style of the API of Net::HTTP makes it difficult to take advantage of persistent connections. The user has to store the created connection and manually handle restarting the connection if it has timed out or is closed by the server.</p>
<p>RFC 2616 8.1.1 has a large section explaining the benefits of persistent connections, but while Net::HTTP implements persistent connections they could be easier for users to implement with next work.</p>
<p>I've implemented support for many of these additional features of Net::HTTP in various projects and I'd like Ruby to have the features required to make a useful HTTP user-agent built-in.</p>
<p>The agent should have the following responsibilities:</p>
<ul>
<li>Make or reuse connections based on [host, port, SSL enabled]</li>
<li>Automatically enable SSL for https URIs</li>
<li>Automatically enable SSL peer verification for SSL connections</li>
<li>Limit number of persistent connections per host</li>
<li>Follow redirects</li>
<li>Retry when a persistent connection fails</li>
<li>Automatically configure proxies</li>
<li>Automatically use authentication</li>
<li>Callbacks for various options connect</li>
</ul>
<p>The agent may add the following responsibilities:</p>
<ul>
<li>Default headers for all requests</li>
<li>HTTP cookies</li>
<li>Tracking history</li>
<li>Logging</li>
</ul>
<p>I don't think any of these features are critical as they are implementable by users via callbacks.</p>
<p>The agent would have the following configurable items:</p>
<ul>
<li>Number of connections per host</li>
<li>Depth of redirects followed</li>
<li>Persistent connection retries (none, HTTP/1.1 (default), always)</li>
<li>Proxy host, port, user, password</li>
</ul>
<p>I think the class should be called Net::HTTP::Agent.</p>
<p>Basic use would look something like this:</p>
<p>uris = [<br>
URI('http://example/1'),<br>
URI('http://example/2'),<br>
URI('https://secure.example'),<br>
]</p>
<p>agent = Net::HTTP::Agent.new</p>
<p>uris.map do |uri|<br>
agent.get uri # Returns Net::HTTPResponse<br>
end</p>
<p>For special requests a Net::HTTPRequest could be constructed:</p>
<p>req = Net::HTTP::Get.new uri.request_uri</p>
<a name="do-something-special-with-req"></a>
<h1 >do something special with req<a href="#do-something-special-with-req" class="wiki-anchor">¶</a></h1>
<p>agent.request req</p>
<p>The agent should support GET, POST, etc. directly through API methods. I think the API should look something like this:</p>
<p>def get uri_or_string, query = nil, headers = nil</p>
<a name="Same-for-other-requests-with-no-body"></a>
<h1 >Same for other requests with no body<a href="#Same-for-other-requests-with-no-body" class="wiki-anchor">¶</a></h1>
<h1></h1>
<a name="query-may-be-a-Hash-or-String"></a>
<h1 >query may be a Hash or String<a href="#query-may-be-a-Hash-or-String" class="wiki-anchor">¶</a></h1>
<a name="How-query-param-vs-query-string-in-URI-is-used-is-undecided"></a>
<h1 >How query param vs query string in URI is used is undecided<a href="#How-query-param-vs-query-string-in-URI-is-used-is-undecided" class="wiki-anchor">¶</a></h1>
<p>def post uri_or_string, data, headers = nil</p>
<a name="same-for-other-requests-with-a-body"></a>
<h1 >same for other requests with a body<a href="#same-for-other-requests-with-a-body" class="wiki-anchor">¶</a></h1>
<h1></h1>
<a name="data-may-be-a-String-IO-or-Hash"></a>
<h1 >data may be a String, IO or Hash<a href="#data-may-be-a-String-IO-or-Hash" class="wiki-anchor">¶</a></h1>
<a name="How-data-format-is-chosen-is-undecided"></a>
<h1 >How data format is chosen is undecided<a href="#How-data-format-is-chosen-is-undecided" class="wiki-anchor">¶</a></h1>
<p>SSL options, proxy options, timeouts and similar options should exist on Net::HTTP::Agent and be set on new connections as they are made.</p>
<p>I've implemented most of these features in mechanize as Mechanize::HTTP::Agent. The Agent class in mechanize is bigger than is necessary and would need to be cut-down for inclusion in Ruby as Net::HTTP::Agent</p>
<p><a href="https://github.com/tenderlove/mechanize/blob/master/lib/mechanize/http/agent.rb" class="external">https://github.com/tenderlove/mechanize/blob/master/lib/mechanize/http/agent.rb</a></p>
<p>Mechanize depends on net-http-persistent to provide HTTP/1.1 retry support and connection management:</p>
<p><a href="https://github.com/drbrain/net-http-persistent/blob/master/lib/net/http/persistent.rb" class="external">https://github.com/drbrain/net-http-persistent/blob/master/lib/net/http/persistent.rb</a></p>
<p>Portions of net-http-persistent should be patches of Net::HTTP, for example #idempotent? #can_retry?, #reset and portions of #request. Other parts (connection management) should be moved to Net::HTTP::Agent.</p>
<p>net-http-persistent provides a separate connection list per thread. I would like Net::HTTP::Agent to be multi-thread friendly but implementing this in another way would be fine.</p>
<p>As an addendum, open-uri and mechanize should be written to take advantage of Net::HTTP::Agent on order to guide useful implementation.</p> Ruby master - Feature #5007 (Assigned): Proc#call_under: Unifying instance_eval and instance_exechttps://bugs.ruby-lang.org/issues/50072011-07-09T23:26:49Zjudofyr (Magnus Holm)judofyr@gmail.com
<p>I'm proposing a method called <code>Proc#call_under</code> (the name could be<br>
discussed) which both unifies <code>instance_eval</code> and <code>instance_exec</code>, and makes<br>
it possible to call a <code>Proc</code> with a block and a scope:</p>
<p><code>Proc#call_under(self, *args, &blk)</code>:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="nb">proc</span> <span class="p">{</span> <span class="nb">self</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># => 1</span>
<span class="nb">proc</span> <span class="p">{</span> <span class="o">|</span><span class="n">a</span><span class="o">|</span> <span class="nb">self</span> <span class="o">+</span> <span class="n">a</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c1"># => 3</span>
<span class="nb">proc</span> <span class="p">{</span> <span class="o">|&</span><span class="n">b</span><span class="o">|</span> <span class="nb">self</span> <span class="o">+</span> <span class="n">b</span><span class="p">.</span><span class="nf">call</span> <span class="p">}.</span><span class="nf">call_under</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="p">{</span> <span class="mi">2</span> <span class="p">}</span> <span class="c1"># => 4</span>
</code></pre> Ruby master - Feature #4824 (Assigned): Provide method Kernel#executed?https://bugs.ruby-lang.org/issues/48242011-06-04T19:59:21Zlazaridis.com (Lazaridis Ilias)ilias@lazaridis.com
<p>The current construct to execute main code looks not very elegant:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">if</span> <span class="kp">__FILE__</span> <span class="o">==</span> <span class="vg">$0</span>
<span class="n">my_main</span><span class="p">()</span> <span class="c1"># call any method or execute any code</span>
<span class="k">end</span>
</code></pre>
<p>With a <code>Kernel#executed?</code> method, this would become more elegant:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="k">if</span> <span class="n">executed?</span>
<span class="c1">#do this</span>
<span class="c1">#do that</span>
<span class="n">my_main</span><span class="p">()</span>
<span class="k">end</span>
</code></pre>
<p>or</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="n">main</span><span class="p">()</span> <span class="k">if</span> <span class="n">executed?</span>
</code></pre>
<p>This addition would not break any existent behaviour.</p> Ruby master - Feature #4818 (Assigned): Add method marshalable?https://bugs.ruby-lang.org/issues/48182011-06-03T11:07:15Zyimutang (Joey Zhou)
<p>Some objects can not be marshaled. Maybe there should be a method to tell it.</p>
<p>hash = Hash.new {|h,k| k * 2}</p>
<p>this hash can't be marshaled because it has a default proc. If existing such method:</p>
<p>Marshal.marshalable?(hash) #=> method "Marshal.marshalable?"<br>
hash.marshalable? #=> method "Kernel#marshalable?"</p>
<p>If you think the method name hard to spell, maybe get a synonym "dumpable?"</p> Ruby master - Feature #4592 (Assigned): Tempfileを直接保存したいhttps://bugs.ruby-lang.org/issues/45922011-04-21T16:43:31Zxibbar (Takeyuki FUJIOKA)xibbar@gmail.com
<p>=begin<br>
Tempfileは一時ファイルなので、プロセスが消えたり、#closeすると、<br>
ファイルが消えてしまいます。<br>
Tempfileのデータを保存するために<br>
一旦読みだして、書き込み用に別ファイルを開いて、<br>
そこに書きこまなければいけません。<br>
これが小さいファイルだったらいいのですが、<br>
大きいファイルになると、<br>
Tempfile#save みたいなメソッドを用意して、<br>
closeと同時に保存ができると、<br>
読みだして書きこむという無駄をなくすことができます。<br>
10MB程度だったらいいのですが、500MとかのTempfileだと<br>
かなり有効なメソッドだと思います。</p>
<p>#save とか #save! とか、何がいいかは議論の余地があると思います。<br>
=end</p> Ruby master - Feature #4539 (Assigned): Array#zip_withhttps://bugs.ruby-lang.org/issues/45392011-03-30T06:21:32Zcitizen428 (Michael Kohl)citizen428@gmail.com
<p>Inspired by Haskell's <code>zipWith</code> function, I hacked on together for Ruby:</p>
<pre><code class="ruby syntaxhl" data-language="ruby"><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">].</span><span class="nf">zip_with</span><span class="p">([</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="p">:</span><span class="o">+</span><span class="p">)</span> <span class="c1">#=> [7, 7, 7]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">].</span><span class="nf">zip_with</span><span class="p">([</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span> <span class="p">{</span> <span class="o">|</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="o">|</span> <span class="mi">3</span><span class="o">*</span><span class="n">a</span><span class="o">+</span><span class="mi">2</span><span class="o">*</span><span class="n">b</span> <span class="p">}</span> <span class="c1">#=> [15, 16, 17]</span>
</code></pre>
<p>So far I only have a Ruby version of it:</p>
<p><a href="https://gist.github.com/731702b90757e21cadcb" class="external">https://gist.github.com/731702b90757e21cadcb</a></p>
<p>My questions:</p>
<ol>
<li>
<p>Would this method be considered a worthwhile addition to <code>Array</code>?</p>
</li>
<li>
<p>I've never hacked on the C side of Ruby (read some parts of the source though) and my C is quite rusty. I'd like to change that, would somebody be willing to help me turn this into a proper patch?</p>
</li>
</ol> Ruby master - Feature #4521 (Assigned): NoMethodError#message may take very long to executehttps://bugs.ruby-lang.org/issues/45212011-03-25T04:59:14Zadiel.mittmann (Adiel Mittmann)adiel@inf.ufsc.br
<p>=begin<br>
When a non-existing method is called on an object, NoMethodError is risen. If you call #message, however, your code may use up all CPU for a very long time (in my case, up to a few minutes).</p>
<p>I narrowed the problem down to this code in error.c (SVN snapshot) in the function name_err_mesg_to_str():</p>
<p>d = rb_protect(rb_inspect, obj, 0);<br>
if (NIL_P(d) || RSTRING_LEN(d) > 65) {<br>
d = rb_any_to_s(obj);<br>
}</p>
<p>The problem is that, for a complex object, #inspect may take very long to execute, only to have its results thrown away because they will be larger than 65 characters.</p>
<p>Of course I can write a #to_s for all my objects, but the point is that I didn't call #to_s or #inspect, I called #message on an exception object, which then takes a few minutes just to return a short string.</p>
<p>Needless to say, this might be easy to spot in a simple example, but once you're writing a web application that suddenly freezes for one minute with no apparent reason, you're all but clueless as to what's going on. (The first time this happened, I didn't even know that something would eventually show up on the screen -- I thought it was an infinite loop).</p>
<p>Here's an example code that shows this behavior:</p>
<p>require 'nokogiri'<br>
class A<br>
def x<br>
@xml = Nokogiri::XML(File.new('baz.xml', 'rb').read())<br>
foo()<br>
end<br>
end<br>
A.new().x()<br>
a.x</p>
<p>Here, the time it takes for Ruby to print out the message that #foo doesn't exist is proportional to the size of baz.xml.</p>
<p>As a comparison, Python doesn't seem to do this. Take the following code:</p>
<p>class Test:<br>
def <strong>str</strong>(self):<br>
return "hello"<br>
a = Test()<br>
print a<br>
print a.x()</p>
<p>If you execute it, this is the result:</p>
<p>hello<br>
Traceback (most recent call last):<br>
File "test.py", line 6, in <br>
print a.x()<br>
AttributeError: Test instance has no attribute 'x'</p>
<p>It uses the method <strong>str</strong> to convert the object to a string when necessary, but doesn't use it when printing out the message stating that the attribute doesn't exist.</p>
<p>One obvious way to fix this would be to always print out the simpler representation given by rb_any_to_s.<br>
=end</p> Ruby master - Feature #4514 (Assigned): #deep_clone and #deep_dup for Objectshttps://bugs.ruby-lang.org/issues/45142011-03-21T19:23:02Zwardrop (Tom Wardrop)tom@tomwardrop.com
<p>=begin<br>
There's often a need to do a deep clone of an object, especially of Hash/Array trees. The typical work around to the lack of this functionality is to Marshall and then Unmarshall (e.g. Marshal::load(Marshal::dump(self)) ), which incurs more overhead than it probably should, and is not very semantic. My suggestion is to either provide #deep_clone and #deep_dup methods on the Object class, or to at least provide equivalent functionality for Hashes and Arrays, such as possibly a #deep_merge method for Hash. The exact implantation is not a large concern of mine; I'll let the experts determine the best method of achieving the desired outcome.<br>
=end</p>