Ruby 检查数组中所有单词的第一个字符,并返回以eg";a或etc“;阵列中

Ruby 检查数组中所有单词的第一个字符,并返回以eg";a或etc“;阵列中,ruby,Ruby,我试图找到数组中的第一个字符,它由几个单词组成 我知道所有的单词,但我不知道如何检查所有单词的第一个字符 def strange_words(words) newarray = [] i = 0 while i < words.length letters = words[i] if ???? #problem is here end i += 1 end return newarray end puts strange_wo

我试图找到数组中的第一个字符,它由几个单词组成

我知道所有的单词,但我不知道如何检查所有单词的第一个字符

def strange_words(words)
  newarray = []
  i = 0
  while i < words.length
    letters = words[i]
    if ???? #problem is here

    end 
    i += 1
  end
  return newarray   
end

puts strange_words(["eating", "period", "value", "earth"])
def奇怪的单词(单词)
newarray=[]
i=0
而我则是
例如,值中的第一个字符是“v”,我想要它。 谢谢

正是这样做的。它返回与块中的条件匹配的第一个元素:

您可以创建如下方法:

def first_word_starting_with(array, characters)
  array.find { |el| el.start_with? characters }
end

arr = ["eating", "period", "value", "earth"]
first_word_starting_with(arr, "v")
# => "value"
确实如此。它返回与块中的条件匹配的第一个元素:

您可以创建如下方法:

def first_word_starting_with(array, characters)
  array.find { |el| el.start_with? characters }
end

arr = ["eating", "period", "value", "earth"]
first_word_starting_with(arr, "v")
# => "value"
返回一个新数组,该数组包含ary的所有元素,给定块将为其返回一个真值

输出:

strange_words(["eating", "period", "value", "earth"], 'ea') 
#=> ["eating", "earth"]
Cheers

返回一个新数组,该数组包含ary的所有元素,给定块将为其返回一个真值

输出:

strange_words(["eating", "period", "value", "earth"], 'ea') 
#=> ["eating", "earth"]

干杯

我假设所有具有所需属性的单词都将以数组形式返回,而不仅仅是第一个这样的单词。这个问题并不清楚,这反映在不同的答案中

def strange_words(words, begins_with)
  words.grep /\A#{begins_with}/
end

words = ["eating", "period", "value", "earth", "vortex", "evenly"]

strange_words(words, "v")
  #=> ["value", "vortex"]
strange_words(words, "ea")
  #=> ["eating", "earth"]
strange_words(words, "z")
  #=> []
看。正则表达式的内容是:“匹配字符串(
\A
)的开头,然后匹配
的值开头为
”的字符串

如果只返回第一个匹配项,一个选项是使
grep
成为惰性枚举数,以便在找到第一个匹配项后停止搜索:

def strange_words(words, begins_with)
  words.lazy.grep(/\A#{begins_with}/).first
end
strange_words(words, "v")
  #=> "value"

我假设所有具有所需属性的单词都将在数组中返回,而不是仅返回第一个这样的单词。这个问题并不清楚,这反映在不同的答案中

def strange_words(words, begins_with)
  words.grep /\A#{begins_with}/
end

words = ["eating", "period", "value", "earth", "vortex", "evenly"]

strange_words(words, "v")
  #=> ["value", "vortex"]
strange_words(words, "ea")
  #=> ["eating", "earth"]
strange_words(words, "z")
  #=> []
看。正则表达式的内容是:“匹配字符串(
\A
)的开头,然后匹配
的值开头为
”的字符串

如果只返回第一个匹配项,一个选项是使
grep
成为惰性枚举数,以便在找到第一个匹配项后停止搜索:

def strange_words(words, begins_with)
  words.lazy.grep(/\A#{begins_with}/).first
end
strange_words(words, "v")
  #=> "value"

有用的,为答案高兴有用的,为答案高兴得到了,非常有用的,非常有用的