将字符串拆分为数组ruby

时间:2016-04-23 18:06:08

标签: ruby oop

我正在尝试将此字符串

<table>
  <tr>
      <td>
          <div id="open" class="opener" data-toopen="course1">course 1 +</div>
      </td>
      <td colspan="4">
          <div id="course1" style="display: none">
              Here is the text
              <div class="close"><br/>X</div>
          </div>
      </td>
  </tr>
</table>

$(function(){
    $('.opener').click(function(){
    var divToOpen = $(this).data('toopen'); / get the id */
    $('#' + divToOpen).slideToggle(); /* this toggles it up and down so close not needed */
  });
  $('.close').click(function(){ /* but if you want close button that's ok too */
    $(this).parent().slideUp(); /* slide it back up */
  })
})

进入这个数组..

"a,bc,c"

我在逗号&amp;上使用了split迭代通过它,但我想找到一个更清洁的方式。

谢谢!

2 个答案:

答案 0 :(得分:3)

我将使用#scan#uniq方法。

"a, bc,c".scan(/[a-z]/).uniq
# => ["a", "b", "c"]

答案 1 :(得分:2)

我们先来看一个选项:

"a, bc,c".gsub(/\W+/, '').chars.uniq

 # Outputs:
 => ["a", "b", "c"]