Ruby 数组中最长的单词

发布于 2024-10-20 17:04:41 字数 904 浏览 6 评论 0原文

我构建这个方法是为了查找数组中最长的单词,但我想知道是否有更好的方法来完成它。我对 Ruby 还很陌生,只是将其作为学习 inject 方法的练习。

它返回数组中最长的单词,或相等最长单词的数组。

class Array
  def longest_word
    # Convert array elements to strings in the event that they're not.
    test_array = self.collect { |e| e.to_s }
    test_array.inject() do |word, comparison|
      if word.kind_of?(Array) then
        if word[0].length == comparison.length then
          word << comparison
        else
          word[0].length > comparison.length ? word : comparison
        end
      else
        # If words are equal, they are pushed into an array
        if word.length == comparison.length then
          the_words = Array.new
          the_words << word
          the_words << comparison
        else
          word.length > comparison.length ? word : comparison
        end
      end
    end
  end
end

I built this method to find the longest word in an array, but I'm wondering if there's a better way to have done it. I'm pretty new to Ruby, and just did this as an exercise for learning the inject method.

It returns either the longest word in an array, or an array of the equal longest words.

class Array
  def longest_word
    # Convert array elements to strings in the event that they're not.
    test_array = self.collect { |e| e.to_s }
    test_array.inject() do |word, comparison|
      if word.kind_of?(Array) then
        if word[0].length == comparison.length then
          word << comparison
        else
          word[0].length > comparison.length ? word : comparison
        end
      else
        # If words are equal, they are pushed into an array
        if word.length == comparison.length then
          the_words = Array.new
          the_words << word
          the_words << comparison
        else
          word.length > comparison.length ? word : comparison
        end
      end
    end
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

看春风乍起 2024-10-27 17:04:41

我会做

class Array
  def longest_word
    group_by(&:size).max.last
  end
end

I would do

class Array
  def longest_word
    group_by(&:size).max.last
  end
end
贵在坚持 2024-10-27 17:04:41

Ruby 有一个标准方法,用于返回列表中具有最大值的元素。

anArray.max{|a, b| a.length <=> b.length}

或者可以使用 max_by 方法

anArray.max_by(&:length)

获取所有最大长度的元素

max_length = anArray.max_by(&:length).length
all_with_max_length = anArray.find_all{|x| x.length = max_length}

Ruby has a standard method for returning an element in a list with the maximum of a value.

anArray.max{|a, b| a.length <=> b.length}

or you can use the max_by method

anArray.max_by(&:length)

to get all the elements with the maximum length

max_length = anArray.max_by(&:length).length
all_with_max_length = anArray.find_all{|x| x.length = max_length}
一梦等七年七年为一梦 2024-10-27 17:04:41

这是使用 inject 的一个(不适用于空数组):

words.inject(['']){|a,w|
  case w.length <=> a.last.length
  when -1
    a
  when 0
    a << w
  when 1
    [w]
  end
}

可以将其缩短为。

words.inject(['']){|a,w|
  [a + [w], [w], a][w.length <=> a.last.length]
}

对于那些喜欢高尔夫的人来说,

Here's one using inject (doesn't work for an empty array):

words.inject(['']){|a,w|
  case w.length <=> a.last.length
  when -1
    a
  when 0
    a << w
  when 1
    [w]
  end
}

which can be shortened to

words.inject(['']){|a,w|
  [a + [w], [w], a][w.length <=> a.last.length]
}

for those who like golf.

赠意 2024-10-27 17:04:41

两行:

vc = ['asd','s','1234','1235'].sort{|a,b| b.size <=> a.size}
vc.delete_if{|a| a.size < vc.first.size} 


#Output
["1235", "1234"]

或者如果你想使用注入,这使用你的想法,但它更短。

test_array.inject{ |ret,word|
   ret = [ret] unless ret.kind_of?(Array)

   ret << word  if word.size == ret.first.size
   ret = [word] if word.size > ret.first.size
   ret
}

A two liner:

vc = ['asd','s','1234','1235'].sort{|a,b| b.size <=> a.size}
vc.delete_if{|a| a.size < vc.first.size} 


#Output
["1235", "1234"]

or if you want use inject, this use your idea, but its more short.

test_array.inject{ |ret,word|
   ret = [ret] unless ret.kind_of?(Array)

   ret << word  if word.size == ret.first.size
   ret = [word] if word.size > ret.first.size
   ret
}
遗失的美好 2024-10-27 17:04:41
module Enumerable
  def longest_word
    (strings = map(&:to_s)).
      zip(strings.map(&:length)).
      inject([[''],0]) {|(wws, ll), (w, l)|
        case  l <=> ll
        when -1 then [wws, ll] 
        when  1 then [[w], l]
        else         [wws + [w], ll]
        end
      }.first
  end
end

此方法仅依赖于通用的 Enumerable 方法,没有任何 Array 特定的内容,因此我们可以将其拉入 Enumerable 模块,其中它也可用于SetEnumerator,而不仅仅是Array

module Enumerable
  def longest_word
    (strings = map(&:to_s)).
      zip(strings.map(&:length)).
      inject([[''],0]) {|(wws, ll), (w, l)|
        case  l <=> ll
        when -1 then [wws, ll] 
        when  1 then [[w], l]
        else         [wws + [w], ll]
        end
      }.first
  end
end

This method only depends on generic Enumerable methods, there's nothing Array specific about it, therefore we can pull it up into the Enumerable module, where it will also be available for Sets or Enumerators, not just Arrays.

℉服软 2024-10-27 17:04:41

该解决方案使用注入方法累积数组中最长的字符串,然后选择长度最大的字符串。

动物 = ["老鼠", "猫", "鸟", "熊", "驼鹿"]

Animals.inject(Hash.new{|h,k| h[k] = []}) { |acc, e | acc[e.size] << e; acc }.sort.last[1]

这将返回:
[“鼠标”,“鼠标”]

This solution uses the inject method to accumulate the longest strings in an array, then picks the ones with the highest length.

animals = ["mouse", "cat", "bird", "bear", "moose"]

animals.inject(Hash.new{|h,k| h[k] = []}) { |acc, e| acc[e.size] << e; acc }.sort.last[1]

This returns:
["mouse", "mouse"]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文