TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Mind blowing Ruby String#split bug?

4 点作者 sm_sohan超过 10 年前
Ran into a weird bug because of this:<p>&gt; x = &quot;<i>a</i>&quot;<p>=&gt; &quot;<i>a</i>&quot;<p>&gt; x.split(&#x27;*&#x27;)<p>=&gt; [&quot;&quot;, &quot;a&quot;]<p>Expected =&gt; [&quot;&quot;, &quot;a&quot;, &quot;&quot;] or [&quot;a&quot;]<p>It feels bizarre. Anyone has an explanation for this?

3 条评论

petercooper超过 10 年前
Assuming by the notation you mean what jordsmi says and you mean:<p><pre><code> x = &quot;*a*&quot; </code></pre> .. then it&#x27;s not surprising. It works similarly with anything, not just asterisks. For example:<p><pre><code> &quot;,a,&quot;.split(&quot;,&quot;) # =&gt; [&quot;&quot;, &quot;a&quot;] </code></pre> But I don&#x27;t consider this behavior odd, and it&#x27;s been the same behavior all the way from 1.8.6 (the oldest implementation I have installed to test with) through 2.2.<p>Think about what&#x27;s necessary when splitting up a row of CSV, say (or even some space limited logs or configs). You want that first &#x27;missing&#x27; value to be represented in the output as it affects the position of later values. However, you don&#x27;t need the final missing value represented as it has no significance - it&#x27;s merely a trailing null value.<p>Also remember that Ruby has its heritage in Perl with methods like this, and Perl behaves similarly:<p><pre><code> perl -e &quot;print join(&#x27;:&#x27;, split(&#x27;\*&#x27;, &#x27;*a*&#x27;));&quot; # =&gt; &quot;:a&quot;</code></pre>
jordsmi超过 10 年前
For people not being able to recreate this is because he doesn&#x27;t mean x = &quot;a&quot; he means x = &quot;yay&quot; with y being asterisks.<p>So<p>x = &quot;yay&quot;<p>x.split(&quot;y&quot;)<p>=&gt; [&quot;&quot;, &quot;a&quot;]
Adkron超过 10 年前
This must be an older version of Ruby. I can&#x27;t reproduce the issue.
评论 #8967607 未加载