如何使用Ruby从数组中删除空格

时间:2018-03-14 11:32:49

标签: ruby

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar fixed-top navbar-dark navbar-expand-sm">
  <a class="navbar-brand" href="#">
    <img src="/images/MW-logo-white.png" height=28 class="" />
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar">
        <span class="navbar-toggler-icon"></span>
      </button>
  <div class="collapse navbar-collapse flex-column align-items-start" id="navbar">
    <ul class="navbar-nav nav my-1 w-100">
      <li class="nav-item">
        <a class="nav-link active" data-toggle="tab" href="#property-tab">PROPERTY</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#units-tab">UNITS</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#tenancies-tab">TENANCIES</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#pdfs-tab">PDFs</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#contacts-tab">CONTACTS</a>
      </li>
      <form class="form-inline ml-auto">
        <input class="form-control search" type="text" id="search-bar" placeholder="Search..." autocomplete="off" spellcheck="false" autocorrect="off" />
      </form>
    </ul>
    <ul class="navbar-nav nav my-1">
      <li class="nav-item">
        <a href="#" class="nav-link active">ALL</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link">CURRENT</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link">PAST</a>
      </li>
    </ul>
  </div>
</nav>

我想像这样打印数组 -

Arr= ["abcd","1223","  10829380","pqrs"]

2 个答案:

答案 0 :(得分:3)

您应该遵循命名模式,而不是使用Arr,因为这通常是使用的 对于班级名称。

arr = ["abcd","1223"," 10829380","pqrs"]
whitespace_removed_arr = arr.map { |item| item.strip }

map迭代字符串数组(arr)并构建一个包含块返回值的新数组。

如果您愿意,可以使用较短的版本:

arr = ["abcd","1223"," 10829380","pqrs"]
whitespace_removed_arr = arr.map(&:strip)

请注意,提出strip!map(iof strip的原位版本)的解决方案很可能在strip!之后无法正常工作或工作(奇怪的是) )当字符串未更改时返回nil

"".strip => ""
"".strip! => nil
"".strip => ""
" ".strip! => ""

如果您想使用条带的inplace变体并修改原始数组,则需要使用each

arr.each(&:strip!)

each会丢弃该块的返回值,而strip!会修改该字符串。

答案 1 :(得分:1)

您可以使用Array#map!Array.mapArray#map!更改原始数组,Array#map返回一个新数组,以便原始数组保持不变。 map函数迭代数组并为数组中的每个元素执行给定的块。

arr = ["abcd", "1223", " 10829380", "pqrs"]
arr.map!{ |el| el.strip }
arr
# => ["abcd", "1223", "10829380", "pqrs"]

# or

arr = ["abcd", "1223", " 10829380", "pqrs"]
arr.map{ |el| el.strip }
# => ["abcd", "1223", "10829380", "pqrs"]
arr
# => ["abcd", "1223", " 10829380", "pqrs"]

Btw:ruby中的变量以小写字母或_(arr)开头。