我必须创建一个程序,接受用户输入的两个单词,并从这两个提取唯一的字母.

两个词是"外推"和"中间".

go 掉常见字母后,无论输入单词的顺序如何,结果都应该是"外推".在外推法中,虽然有两个‘a’,但只go 掉了一个..

我写的代码直到现在都是在

puts "Enter the first_word : "

word_1 = gets.chomp.downcase.split('', 0)


puts "Enter second word name: "

word_2 = gets.chomp.downcase.split('', 0)

p word_1

p word_2

differences = word_1- word_2

p differences

#input1 = among
#input2 = extrapolation

# output => ["m","g"] 


代码忽略第二个单词中不在第一个单词中的字母.

有没有内置的字符串方法来处理这个问题?

提前感谢你的帮助..

推荐答案

假设给我们两个词.

w1 = "extrapolation"
w2 = "among"

Step 1: Convert each of these strings to an array of characters

a1 = w1.chars
  #=> ["e", "x", "t", "r", "a", "p", "o", "l", "a", "t", "i", "o", "n"]
a2 = w2.chars
  #=> ["a", "m", "o", "n", "g"]

Step 2: Create a hash for each array that gives the index of the first instance of each unique character in the array

def first_char_pos(a)
  a.each_with_index.with_object({}) do |(c,i),h|
    h[c] = i unless h.key?(c)
  end
end
h1 = first_char_pos(a1)
  #=> {"e"=>0, "x"=>1, "t"=>2, "r"=>3, "a"=>4,
  #    "p"=>5, "o"=>6, "l"=>7, "i"=>10, "n"=>12}
h2 = first_char_pos(a2)
  #=>{"a"=>0, "m"=>1, "o"=>2, "n"=>3, "g"=>4}

Step 3: Identify the letters to be removed from each word

letters_to_remove = a1 & a2
  #=> ["a", "o", "n"]

Step 4: Identify the indices of the letters in each word to keep

def indices_to_keep(a, h, letters_to_remove)
  a.size.times.to_a - h.values_at(*letters_to_remove)
end
idx1 = indices_to_keep(a1, h1, letters_to_remove)
  #=>[0, 1, 2, 3, 5, 7, 8, 9, 10, 11]
idx2 = indices_to_keep(a2, h2, letters_to_remove)
  #=> [1, 4]

Step 5: Identify, in order, the letters in each word to keep

s1 = a1.values_at(*idx1)
  #=> ["e", "x", "t", "r", "p", "l", "a", "t", "i", "o"]
s2 = a2.values_at(*idx2)
  #=> ["m", "g"]

Step 6: Form the desired string

s1.join + s2.join
  #=> "extrplatiomg"

这与所需的字符串不同,后者为"extrpolatimg".原因是我删除了要删除的每个字母的第一个实例,而所需的字符串是通过删除每个字符串的第一个"a"和最后一个"o"来获得的.要么是OP在给出想要的结果时出错,要么是我不理解确定要删除字母的哪个实例的规则.

我没有提到可能出现大写字母的情况,因为我不知道在这种情况下适用的规则.

Ruby相关问答推荐

警告 Selenium [弃用] Manager#logs 已弃用.使用 Chrome::Driver#logs 代替

多线程期间的 MRI ruby​​ 内存访问特性

使用 Drive API 创建空文件

RVM 和 OpenSSL 的问题

创建线程安全的临时文件名

如何在 ruby​​ 中通过 SSL 调用 HTTP POST 方法?

如何将两周时间添加到 Time.now?

将参数传递给erb视图

为什么 Ruby 使用 respond_to?而不是 responds_to?

Rails - create and create!

Ruby 和您必须使用 OpenSSL 支持重新编译 Ruby 或更改 Gemfile 中的源代码

迭代一个数组,一次 n 项

STDERR.puts 与 Ruby 中的 puts 有何不同?

获取类中声明的所有实例变量

从命令行使用Bundle 器将 gem 添加到 gemfile

Ruby 将 CSV 文件读取为 UTF-8 和/或将 ASCII-8Bit 编码转换为 UTF-8

为什么 Ruby 文档中的方法前面有一个井号?

如何使用 link_to Ruby on rails 添加确认消息

如何在 Rails 3 迁移中描述枚举列?

def `self.function` 名称是什么意思?