簡體   English   中英

我可以在Ruby的String類中使用String類的方法嗎?

[英]Can I use methods for String class within the String class in Ruby?

我在ruby中使用字符串對象的新方法應該返回字符串中每個字符計數的哈希值(從.txt文件加載),我可能正在嘗試以一種簡單的方式進行處理,但是我可以似乎可以在不傳遞對象的情況下使其工作。 我想知道是否有一種方法可以不傳遞字符串。 任何幫助,將不勝感激。

這是我的代碼

class String
  def frequency
    Object.downcase
    Object.gsub("\n", " ")
    h = {}
    h["A:"] = Object.count('a')
    h["B:"] = Object.count('b')
    h["C:"] = Object.count('c')
    h["D:"] = Object.count('d')
    h["E:"] = Object.count('e')
    h["F:"] = Object.count('f')
    h["G:"] = Object.count('g')
    h["H:"] = Object.count('h')
    h["I:"] = Object.count('i')
    h["J:"] = Object.count('j')
    h["K:"] = Object.count('k')
    h["L:"] = Object.count('l')
    h["M:"] = Object.count('m')
    h["N:"] = Object.count('n')
    h["O:"] = Object.count('o')
    h["P:"] = Object.count('p')
    h["Q:"] = Object.count('q')
    h["R:"] = Object.count('r')
    h["S:"] = Object.count('s')
    h["T:"] = Object.count('t')
    h["U:"] = Object.count('u')
    h["V:"] = Object.count('v')
    h["W:"] = Object.count('w')
    h["K:"] = Object.count('x')
    h["Y:"] = Object.count('y')
    h["Z"] = Object.count('z')
return h
end
end

聽起來您在談論self ,這是引用當前對象的ruby關鍵字。 請注意,如果僅調用方法,則隱含self 所以用你的例子

class String
  def frequency
    count('a')
  end
end

將返回的數量a字符串以s

"asdfa".frequency #=> 2

只是一個注意事項,但是您當前的方法是非常重復的,您可能需要考慮利用循環來減少代碼量。 另外你不算大寫字母:)

這是我使用的版本,是Rosetta Letter Frequency的完整副本:

#!/usr/bin/env ruby
def letter_frequency(string)
    freq = Hash.new(0)
    string.each_char.lazy.grep(/[[:alpha:]]/).map(&:upcase).each_with_object(freq) do |char, freq_map|
        freq_map[char] += 1
    end
end

在ruby中,您可以打開類並添加方法,例如:

class String
   def my_method
       my_method_code
   end
end

然后,您只需調用方法string.my_method 但是,在您的情況下,我寧願使用Ruby模塊 這是一個代碼示例,與一個類非常相似,但是更干凈,恕我直言:

#!/usr/bin/env ruby

module MyString
    def self.letter_frequency(string)
        freq = Hash.new(0)
        string.each_char.lazy.grep(/[[:alpha:]]/).map(&:upcase).each_with_object(freq) do |char, freq_map|
            freq_map[char] += 1
        end
        return freq
    end
end

p MyString.letter_frequency('absd')

模塊更適合於將自己的類添加到項目中,從而避免名稱沖突和創建混合。

而不是使用非常長的,非DRY的方法將您的對象重復26次,如何使用一些Ruby:

def frequency
  Hash[downcase.gsub(/[^a-z]/,'').chars.group_by(&:to_s).map{|char, group| ["#{char.upcase}:", group.size]}]
end

如果發現它更易於閱讀(並查找API [1]中的方法),則可以將其分成幾行:

def frequency
  intermediate_variable = downcase
  intermediate_variable = intermediate_variable.gsub(/[^a-z]/,'') # only keep a-z characters
  intermediate_variable = intermediate_variable.chars.group_by(&:to_s) # split the string into its component characters and then group that array by the characters (run this on an array to see what it does :-)  could also have written it `.group_by{|e|e}`
  intermediate_variable = intermediate_variable.map{|char, group| ["#{char.upcase}:", group.size]} # map the array of grouped characters into an array of character and counts (formatting the 'character' how you would like your hash key configured
  Hash[intermediate_variable] # make a hash of the characters and their counts
end

[1] http://ruby-doc.org/core-2.0.0/Enumerable.html http://ruby-doc.org/core-2.0.0/String.html

我只是創建一個像這樣的哈希:

class String 
  def frequency
    chars.each_with_object(Hash.new(0)) do |char, h|
      h["#{char.upcase}:"] += 1 if char[/[[:alpha:]]/]
    end
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM