输入str = "This is my string. We need to truncate this string to certain length"
输出str = "this-is-my-string-we-need"
我尝试了这个,但是需要一点点有效的代码:
str.split(" ").map{ |word| word + "-"}.join()
答案 0 :(得分:2)
我假设您的字符串将是正确的文本,但也许可以有句号(。),逗号(,),问号(?)和惊叹号(!)。根据您提供的示例,其中省略了句号,我想您正在删除这些特殊字符。
因此,这里很少尝试达到您的情况,
str = "This is my string. We need to truncate this string to certain length"
str.downcase.gsub(/[^0-9A-Za-z\s]/, '').gsub(/\s+/, '-')
# => "this-is-my-string-we-need-to-truncate-this-string-to-certain-length"