如果字符串包含元音,则输出字符串,并且按字母顺序排列

时间:2014-01-03 23:58:06

标签: ruby arrays string sorting

我正在进行以下练习:

编写一个方法ovd(str),它接受​​一串小写单词并返回一个字符串,其中只包含按字母顺序排列所有元音(不包括“y”)的单词。可以重复元音("afoot"是有序的元音字)。如果不是按字母顺序排列,则该方法不返回该单词。

示例输出是:

  

ovd(“这是对元音排序系统的测试”)#output => “这是对系统的测试”

     

ovd(“复杂”)#output => “”

下面是我写的代码,它将完成这项工作,但我希望看看是否有更短的更聪明的方法来做到这一点。我的解决方案似乎太冗长了。谢谢你提前帮忙。

def ovd?(str) 
  u=[] 
  k=str.split("")   
  v=["a","e","i","o","u"]
  w=k.each_index.select{|i| v.include? k[i]}
  r={}
  for i in 0..v.length-1
     r[v[i]]=i+1
  end
  w.each do |s|
     u<<r[k[s]]
  end
   if u.sort==u 
      true
  else 
      false
  end

end

def ovd(phrase) 
  l=[]
  b=phrase.split(" ") 
  b.each do |d|
    if ovd?(d)==true
    l<<d 
    end
  end
  p l.join(" ") 
end

2 个答案:

答案 0 :(得分:3)

def ovd(str)
  str.split.select { |word| "aeiou".match(/#{word.gsub(/[^aeiou]/, "").chars.uniq.join(".*")}/) }.join(" ")
end
ovd("this is a test of the vowel ordering system") # => "this is a test of the system"
ovd("complicated") # => ""
ovd("alooft") # => "alooft"
ovd("this is testing words having something in them") # => "this is testing words having in them"

修改

根据OP的要求,解释

String#gsub word.gsub(/ [^ aeiou] /,“”)删除非元音字符,例如     “afloot”.gsub(/ [^ aeiou] /,“”)#=&gt; “AOO” String#chars将新单词转换为字符数组

"afloot".gsub(/[^aeiou]/, "").chars # => ["a", "o", "o"]

Array#uniq转换只返回数组中的唯一元素,例如

"afloot".gsub(/[^aeiou]/, "").chars.uniq # => ["a", "o"]

Array#join将数组转换为字符串,将其与提供的参数合并,例如

"afloot".gsub(/[^aeiou]/, "").chars.uniq.join(".*") # => "a.*o"  

#{}只是String interpolation并且//将插值字符串转换为正则表达式

/#{"afloot".gsub(/[^aeiou]/, "").chars.uniq.join(".*")}/ # => /a.*o/

答案 1 :(得分:1)

非正则表达式解决方案:

V = %w[a e i o u] # => ["a", "e", "i", "o", "u"]

  def ovd(str)
    str.split.select{|w| (x = w.downcase.chars.select \
      {|c| V.include?(c)}) == x.sort}.join(' ')
  end

  ovd("this is a test of the vowel ordering system")
                                          # => "this is a test of the system"
  ovd("")                                 # => ""
  ovd("camper")                           # => "camper" 
  ovd("Try singleton")                    # => "Try"
  ovd("I like leisure time")              # => "I" 
  ovd("The one and only answer is '42'")  # => "The and only answer is '42'"
  ovd("Oil and water don't mix")          # => "and water don't mix" 

编辑以添加替代方案:

NV = (0..127).map(&:chr) - %w(a e i o u) # All ASCII chars except lc vowels

def ovd(str)
  str.split.select{|w| (x = w.downcase.chars - NV) == x.sort}.join(' ')
end

注意x = w.downcase.chars & V不起作用。当它从w中剔除元音并保留其顺序时,它会删除重复项。