Ruby 使用JSON中的随机值而不重复它们?

Ruby 使用JSON中的随机值而不重复它们?,ruby,regex,json,Ruby,Regex,Json,我正在编写一个小Ruby Sinatra应用程序,它以一种疯狂的Libs类型的方式用正则表达式替换字符串片段。我正在加载一个JSON对象以获取字符串,并使用“sample”方法获取随机值。这并不能解决只使用一次值的问题。有人能帮忙吗 资料来源: get '/' do paragraph = "" vocab = JSON.parse(File.read('music-journalism-vocabulary.json')) artist_types = ["male","fe

我正在编写一个小Ruby Sinatra应用程序,它以一种疯狂的Libs类型的方式用正则表达式替换字符串片段。我正在加载一个JSON对象以获取字符串,并使用“sample”方法获取随机值。这并不能解决只使用一次值的问题。有人能帮忙吗

资料来源:

get '/' do

  paragraph = ""

  vocab = JSON.parse(File.read('music-journalism-vocabulary.json'))

  artist_types = ["male","female","plural"]

  artist = ""
  artist_type = artist_types.delete artist_types.sample
  artist = vocab["artist-#{artist_type}"].sample
  case artist_type
  when "male"
    artist_posessive_pronoun = "his"
  when "female"
    artist_posessive_pronoun = "her"
  when "plural"
    artist_posessive_pronoun = "their"
  else
  end

  sentences = []
  sentences << vocab["sentence-intro"].sample
  sentences << vocab["sentence-middle"].sample
  sentences << vocab["sentence-conclusion"].sample

  sentences.each_with_index do |iter, i|
    sentence = iter.dup
    sentence_with_replacement = sentence.dup

    # Handle plural agreement
    if (artist_type == "plural")
      sentence_with_replacement.gsub!(/\*artist-subject\*/, "*artist-subject*s")
    end

    word_types = vocab.keys
    word_types.each_with_index do |word_type, j|

      sentence = ''
      while sentence != sentence_with_replacement do
        sentence = sentence_with_replacement.dup
        sentence_with_replacement = sentence.sub(/\*#{word_type}\*/, vocab[word_type].sample)
      end
    end

    sentence_with_replacement.gsub!(/\*artist\*/, artist)
    # Subject-pronoun agreement
    sentence_with_replacement.gsub!(/\*posessive-pronoun\*/, artist_posessive_pronoun)

    sentence_with_replacement[0] = sentence_with_replacement.capitalize[0]
    paragraph << "#{sentence_with_replacement} "
  end

  paragraph

end

谢谢。

您可以在数组中定义一个新方法(我们使用!表示修改了原始数组):


请将代码的相关部分(即可运行的最小示例)发布到您的问题中,以便当您的代码在Github上更改时,它仍然与其他用户相关。这也有助于我们了解您真正想要实现的目标以及您的实际问题。您是否可以将替换项存储在列表中,并在替换之前检查列表,看看列表中是否已经存在该替换项?这听起来像是“洗牌”问题的另一个实例,其中有几个很好的问题和答案已经在网站上。如果有具体的限制(如单词集合特别大),请详细说明。否则,最好的解决方法可能是将集合(或索引或键列表,如果合适)无序排列,然后从该列表中选取前n个项。
{
    "artist-male": ["Skrillex",
                "Bon Iver",
                "A$AP Rocky",
                "Earl Sweatshirt",
                "Frank Ocean"
              ],
    "artist-female": ["Grimes"
              ],
    "artist-plural": ["Death Grips",
                    "Best Coast",
                    "Toro Y Moi",
                    "Odd Future",
                    "Gold Panda",
                    "Icona Pop",
                    "Foxygen",
                    "Four Tet"
              ],

    "adverb": [
        "inarguably",
        "inevitably",
        "reliably",
        "positively",
        "truly",
        "genuinely",
        "sharply",
        "intricately",
        "hopelessly"
    ],
    "adjective": [
        "chrome-plated",
        "lonely",
        "mossy",
        "poised",
        "lysergic",
        "solid-state",
        "lyrical",
        "id-driven",
        "rubbery",
        "hard",
        "striated",
        "electroacoustic",
        "tarnished",
        "radiophonic",
        "wispy",
        "soul-deep",
        "minimal",
        "lulling",
        "insular",
        "nostalgic",
        "vacant",
        "feminine",
        "sensual",
        "meditative",
        "somnambulant",
        "velvet-gloved",
        "melodic",
        "confessional",
        "rollercoaster",
        "thrilling",
        "crunchy",
        "lush",
        "deranged",
        "shambolic",
        "stalwart",
        "ephemeral",
        "gentle",
        "angular",
        "sanctified",
        "austere",
        "cinematic",
        "focused",
        "sheer",
        "purring",
        "rangy",
        "jittery",
        "world-weary",
        "slippery",
        "colorful",
        "multi-layered",
        "complex",
        "tentative",
        "apocalyptic",
        "eerie",
        "withering",
        "clattering",
        "20th-century",
        "impressionist",
        "Glass-ian",
        "distorted",
        "raw",
        "wild",
        "gleaming",
        "evocative",
        "otherworldly",
        "melancholic",
        "lugubrious",
        "phlegmatic",
        "sanguine",
        "analog",
        "delirious",
        "Aristotelian",
        "slick",
        "rudderless",
        "radio-ready",
        "knotty",
        "demonstrative",
        "thousand-watt"
    ],
    "adjective-prefix": [
        "quasi-",
        "aggro-",
        "hobo-",
        "über-"
    ],
    "comparative": [
        "darker",
        "lonelier",
        "sharper",
        "subtler"
    ],
    "artist-subject": [
        "mannerist",
        "architect",
        "enfant terrible",
        "spectre",
        "vaudevillian",
        "sine qua non"
    ],
    "album-subject": [
        "endeavor",
        "release",
        "amalgamation",
        "offering",
        "approach",
        "diversion",
        "reimagining",
        "capital-A album"
    ],
    "style-noun": [
        "skronk",
        "techno-future",
        "jangle-funk",
        "jungle-metal",
        "Philly-soul",
        "skate-punk",
        "synth-schlock",
        "high-goth",
        "alt-country",
        "Afrobeat",
        "French chanson",
        "pop balladry"
    ],
    "meaning-noun": [
        "legacy",
        "monumentality",
        "séance",
        "splendor",
        "drama",
        "grit",
        "sexiness",
        "mutability",
        "tragedy",
        "grief",
        "ardor",
        "celebration",
        "ennui",
        "euphoria",
        "beauty",
        "majesty",
        "nimbleness",
        "humility",
        "aggression"
    ],
    "meaning-verb": [
        "flaunt",
        "sweep",
        "woo",
        "conjure"
    ],
    "judgement-noun": [
        "confidence",
        "boldness",
        "swagger",
        "vigor",
        "prowess",
        "mastery"
    ],
    "judgement-adjective": [
        "unsurpassed",
        "entrancing",
        "enlightenment-inducing",
        "universal",
        "well-rehearsed",
        "impeccable",
        "revelatory",
        "transcendent",
        "stunning"
    ],
    "judgement-verb": [
        "triumph",
        "succeed",
        "soar",
        "captivate",
        "shimmer"
    ],
    "technique-noun": [
        "white noise",
        "baritone",
        "rhythm guitar",
        "soliloquy",
        "beatbox",
        "crescendo",
        "production",
        "drones",
        "whiplash",
        "showboating",
        "schtick"
    ],
    "technique-noun-plural": [
        "hard angles",
        "pulsations",
        "bons mots",
        "verbal gymnastics",
        "grooves",
        "strings",
        "drones",
        "acerbics",
        "harmonies",
        "sonorities",
        "cadences",
        "mantras",
        "vocoders",
        "squelches"
    ],
    "technique-verb": [
        "sway",
        "swagger",
        "assemble",
        "croon",
        "protest",
        "transform",
        "dissolve"
    ],
    "character-phrase": [
      "with money to burn",
      "against all odds",
      "par excellence",
      "for the *non-music-reference* generation",
      "with a yen for *drug*",
      "ready to cash in"
    ],
    "drug": [
      "barbituates",
      "opiates",
      "box wine",
      "laudanum",
      "mescaline",
      "dead-stock quaaludes"
    ],
    "non-music-reference": [
      "Buzzfeed",
      "Twitter",
      "Honey Boo Boo",
      "Hulu",
      "MySpace"
    ],
    "sentence-intro": ["Amid the growing fashionability of *adjective* *technique-noun* and *adjective* *technique-noun*, *artist*'s new *album-subject* distinguishes itself with *meaning-noun* and *judgement-noun*.",
                      "*artist* reappeared with *posessive-pronoun* latest *album-subject* as *adjective* *artist-subject* *character-phrase*."
                      ],
    "sentence-middle": [
        "*posessive-pronoun* latest *album-subject* is discernably *posessive-pronoun* attempt to *technique-verb* the *adjective* *technique-noun-plural* that a more typically *style-noun* *album-subject* would employ, with particular attention paid to the *adjective* delivery of *adjective-prefix**adjective* *meaning-noun*.",
        "*posessive-pronoun* latest *album-subject* is *comparative*, *judgement-adjective*; *adverb* *adjective* and *adjective*, full of *technique-noun* and *adjective* *technique-noun*.",
        "The *adjective* *judgement-noun* of *posessive-pronoun* *adjective* *meaning-noun* *judgement-verb*s, and *posessive-pronoun* *style-noun* *judgement-noun* is *adverb* *judgement-adjective*.",
        "To say *posessive-pronoun* *album-subject* is \"*adjective*\" is a gross understatement—in the hands of *artist*, *style-noun* is *adverb* transformed from *adjective* *meaning-noun* into *adjective*, *adjective-prefix**adjective* *meaning-noun*.",
        "*posessive-pronoun* *judgement-adjective* *album-subject* is *meaning-noun* by design –– *adjective* *style-noun* by way of *judgement-adjective*, *adjective* *technique-noun*.",
        "*posessive-pronoun* new *album-subject* is *adverb* a more *adjective*, *adjective* work than *posessive-pronoun* last, and suggests its *technique-noun-plural* are as much *adjective* as they are *adjective*.",
        "If the opening track *adverb* assumes the *adjective* *technique-noun* of *adjective* *style-noun*, it prefers to *technique-verb* rather than to *technique-verb*.",
        "For all the *adjective* *technique-noun* heard on *posessive-pronoun* last *album-subject*, these performances are for the most part *adjective-prefix**adjective* and *judgement-adjective*, making *posessive-pronoun* songs *comparative* than their *adjective* *technique-noun-plural* initially suggest."
    ],
    "sentence-conclusion": [
        "And, forgiving the obligatory *adjective* *technique-noun*, one can almost detect the *adjective* *style-noun* that might have subsumed this otherwise-*adjective* *style-noun* *meaning-noun*.",
        "Still, seeing these *adjective* songs through their *adjective* *technique-noun-plural* is more than *adjective*, if only for the promised *adjective-prefix**adjective* *technique-noun-plural* and *adjective* *judgement-noun*."
    ]
}
class Array
  def deal!
    self.slice!(rand(self.length-1))
  end
end

foo = [1,2,3,4,5]

puts "deal #{foo.deal!}"
puts "deal #{foo.deal!}"
puts "deal #{foo.deal!}"
puts "deal #{foo.deal!}"
puts "deal #{foo.deal!}"