尝试从字符串RUBY中删除空格

时间:2018-12-21 14:41:53

标签: ruby

正如标题所说,我正在尝试编写一个删除空格的函数。这是我到目前为止的位置,但似乎我缺少了一些东西。

def remove(x)
  if x.include? " "
    x.gsub!(/ /,"")
  end
end

2 个答案:

答案 0 :(得分:3)

我认为您可能正在检查函数的输出,对吧?

你有类似的东西

remove('1q')
=> nil

这是因为如果找不到空间,则remove方法不会返回任何内容。只要确保您返回修改后的值即可。

def remove(x)
  if x.include? " "
    x.gsub!(/ /,"")
  end
  x  # this is the last executed command and so will be the return value of the method
end

现在您将看到

 remove('1q')
=> "1q"

请注意,您的方法实际上是对对象进行了突变,因此您实际上不需要测试返回的内容,只需检查具有原始值的变量即可。做...

test_value = 'My carrot'
remove(test_value)

p test_value
=> "Mycarrot"

最后,正如已经指出的那样,您不需要将其括在if子句中,gsub!仅在找到的任何空间都起作用,否则将无任何作用。

def remove(x)
  x.gsub!(' ', '')
  x
end

请注意,您仍然需要返回x变量,就像gsub!什么都不做一样,它返回nil

方法gsub(不会改变),它将始终返回一个新值,该值将是进行了任何替换的字符串,因此您可以这样做

def remove(x)
  x.gsub(' ','')
end

这将始终返回一个值,而不管是否发生替换...但是原始对象将保持不变。 (返回的值将具有不同的object_id

答案 1 :(得分:1)

更简单,您可以执行以下操作:

def remove_blank_spaces(str)
  str.delete(' ')
end

其他选项:

def remove_blank_spaces(str)
  str.gsub(' ', '')
end