1

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

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

2 回答 2

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

于 2018-12-21T15:03:58.350 回答
1

更简单,你可以这样做:

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

其他选项:

def remove_blank_spaces(str)
  str.gsub(' ', '')
end
于 2018-12-21T14:51:39.473 回答