切换带连字符的单词的顺序

时间:2015-11-02 18:44:39

标签: ruby regex

解析带连字符的单词列表并返回切换的开头和结尾单词的最佳方法是什么?

输入:

spider-man
wonder-woman

输出:

man-spider
woman-wonder

4 个答案:

答案 0 :(得分:4)

您可以拆分它然后反转它。

searchDisplayController is deprecated: first deprecated in iOS 8.0

答案 1 :(得分:3)

你可以使用正则表达式

"spider-man".gsub(/^(.+)-(.+)$/, '\2-\1')
#=> "man-spider"

它将比@ rohit89解决方案慢两倍;)

答案 2 :(得分:2)

您可以使用splitreversejoin

words = ['spider-man', 'super-woman']

words.map do |word|
  word.split('-').reverse.join('-')
end

# => ['man-spider', woman-super']

答案 3 :(得分:2)

看起来是基准时间:

require 'fruity'

STR = 'spider-man'

compare do
  split_reverse_join {STR.split('-').reverse.join('-') }
  regex { STR.gsub(/^(.+)-(.+)$/, '\2-\1') }
end

# >> Running each test 2048 times. Test will take about 1 second.
# >> split_reverse_join is faster than regex by 3x ± 0.1

比较模式的微小变化:

require 'fruity'

STR = 'spider-man'

compare do
  regex1 { STR.gsub(/^(.+)-(.+)$/, '\2-\1') }
  regex2 { STR.gsub(/^([^-]*)-(.+)$/, '\2-\1') }
end
# >> Running each test 1024 times. Test will take about 1 second.
# >> regex1 is similar to regex2

gsubsub进行比较:

compare do
  gsub_regex { STR.gsub(/^(.+)-(.+)$/, '\2-\1') }
  sub_regex { STR.sub(/^(.+)-(.+)$/, '\2-\1') }
end
# >> Running each test 2048 times. Test will take about 1 second.
# >> sub_regex is faster than gsub_regex by 70.0% ± 10.0%

sub总是比gsub快,因为它会在第一次搜索命中后拯救,而不是寻找额外的点击。

  

最快的将是最丑陋的。 pos = str.index("-"); str[pos+1..-1] + "-" + str[0...pos]

compare do
  split_reverse_join {STR.split('-').reverse.join('-') }
  regex { STR.gsub(/^(.+)-(.+)$/, '\2-\1') }
  pos {
    pos = STR.index("-")
    STR[pos+1..-1] + "-" + STR[0...pos]   
  }
end

# >> Running each test 2048 times. Test will take about 1 second.
# >> pos is faster than split_reverse_join by 19.999999999999996% ± 10.0%
# >> split_reverse_join is faster than regex by 3x ± 0.1