在Ruby中比较两个包含字符串的数组

时间:2023-02-06 12:14:11

Forgive me if my code is off. I've still got my head in Ruby on Rails which seems to have subtle differences that are coming out as I learn more "just Ruby," although to be fair I'm not sure my code would pass muster in a Ruby on Rails format. I digress.

如果我的代码关闭了,请原谅我。我仍然在Ruby on Rails中找到了我的头,在我学到更多“只是Ruby”的时候,它似乎有一些细微的差别,尽管我不确定我的代码是否能通过Ruby on Rails格式的集合。我跑题了。

I am trying to compare two arrays that contain a set of strings. I want to do a couple things. 1) Ensure that the arrays are the same number of words, otherwise the exercise is moot. 2) Compare the first word in an array with only the first word in the second array. In other words, I never want to compare word 1 in array "a" with word 4 in array "b". I'm struggling to find a solution that reorders the characters in any given word, compares it to the reordered characters in the corresponding word in the second array, and prints 1 if it's an anagram (once sorted, the idea is that the two words would be equivalent) or 0 if they do not match.

我正在比较包含一组字符串的两个数组。我想做几件事。1)确保数组的字数相同,否则操作就没有意义。2)将数组中的第一个单词与第二个数组中的第一个单词进行比较。换句话说,我不想将数组a中的单词1与数组b中的单词4进行比较。我努力寻找解决方案,重新排列了字符在任何给定的词,与重新排序字符进行比较第二个数组中相应的单词,并打印1如果是一个回文构词法(排序后,我们的想法是,这两个词将等效)或0,如果他们不匹配。

In the example below, what I want it to print is:

在下面的例子中,我想要打印的是:

0
0
1
1

0 0 1 1

...but that is not happening. Thoughts? I'm afraid this has to do with local variable issues, but I am not be sure.

…但这并没有发生。想法吗?恐怕这与局部变量有关,但我不确定。

    a = ['hello', 'goodbye', 'pants', 'baa']
    b = ['helio', 'godbye', 'spant', 'aba']

    x = a.length
    y = b.length
    z = 0

    x = y? do
        while z < x do
            if a.find(z).chars.sort.join == b.find(z).chars.sort.join
                puts 1
            else
                puts 0
            end

            z += 1
        end
    end

4 个解决方案

#1


3  

[Edit: I've edited my answer to incorporate an efficiency improvement suggested by @raph in a comment on the question (the method anagram? below). That may not be necessary, but I thought it was such a good idea that it should get some exposure. I've also given a detailed explanation, as the OP is new to Ruby, as might be other readers.]

[编辑:我编辑了我的答案,将@raph建议的效率改进融入到对问题的评论中(方法anagram?)下文)。这也许不是必须的,但我认为这是一个很好的主意,它应该得到一些曝光。我也给出了详细的解释,因为OP对Ruby来说是全新的,其他读者可能也是如此。

You might consider doing it as follows.

您可以考虑这样做。

Code

代码

def anagrams(a, b)
  return nil unless a.size == b.size
  a.zip(b).map { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
end

def anagram?(aw, bw)
  return false unless aw.size == bw.size
  counts = aw.downcase.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
  bw.downcase.each_char do |c|
    return false unless counts[c] > 0
    counts[c] -= 1
  end
  true
end

Example

例子

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'Spant', 'aba']
anagrams(a, b)
  #=> [0, 0, 1, 1]

Explanation

解释

anagrams method

字谜方法

For the example above,

对于上面的示例,

a.size #=> 4
b.size #=> 4

so we don't return nil in the first line of anagrams.

所以我们不会在字谜的第一行返回nil。

Next,

接下来,

c = a.zip(b)
  #=> [["hello", "helio"], ["goodbye", "godbye"],
  #    ["pants", "Spant"], ["baa", "aba"]]

Assuming for a moment that anagram? works as desired:

假设这是一个字谜?是想要的:

c.map { |e| anagram?(e.first, e.last) ? 1 : 0 }
  #=> [0, 0, 1, 1]

Enumerable#map passes each element of c (a two-element array) into the block.1. It is clearer, however, to decompose (or "disambiguate") those arrays and assign each of the two words they comprise to a block variable2:

Enumerable#map将c(一个双元素数组)中的每个元素都传递到block.1中。但是,更清楚的是,分解(或“消除歧义”)这些数组,并将它们组成的两个单词中的每一个赋值给block variable2:

c.map { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
  #=> [0, 0, 1, 1]

The first element passed in is ["hello", "helio"], so

传入的第一个元素是["hello", "helio"]。

aw => "hello"
bw #=> "helio"

and we execute

我们执行

anagram?("hello", "helio") ? 1 : 0
  #=> 0

which is shorthand for

这是缩写

if anagram?("hello", "helio")
  1
else
  0
end
  #=> 0

anagram? method

回文构词法吗?方法

So now let's move on to anagram?, with

现在我们来看看字母组合?,

aw = "hello"
bw = "helio"

Since

aw.size == bw.size #=> true

we don't return.

我们不回来了。

Count frequency of letters in the first word

计算第一个单词中字母的频率

Let me now write the next few lines of anagram? slightly differently:

下面几行字母组合?略有不同:

counts = Hash.new(0)
  #=> {}
aw_down = aw.downcase 
  #=> "hello"
aw_down.each_char { |c| counts[c] += 1 }
  #=> "hello"
counts
  #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

(The last line is there just to show the value of the hash.)

(最后一行只是显示哈希值)

In the first line we create a hash counts with a default value of zero. All this means is that if counts does not contain the key k, counts[k] will return the default value. Very important: doing so does not change the hash!3

在第一行中,我们创建一个带有默认值为0的散列计数。所有这一切意味着如果计数不包含键k,计数[k]将返回默认值。非常重要:这样做不会改变散列

String#each_char4 passes each character of "hello" into the block and assigns it to the block variable c. Initially, c='h' and h={}. We then execute

字符串#each_char4将“hello”的每个字符传递到块中,并将其分配给块变量c.最初,c='h'和h={}。然后,我们执行

counts['h'] += 1

which is shorthand for

这是缩写

counts['h'] = counts['h'] + 1

Since counts does not yet have a key 'h', counts['h'] on the right returns the default value:

由于count还没有键h,所以右边的counts[h]会返回默认值:

counts['h'] = 0 + 1 #=> 1
counts #=> {"h"=>1}

Similarly, after 'e' and the first 'l' are passed to the block, we have:

类似地,在将'e'和第一个'l'传递给block之后,我们有:

counts #=> {"h"=>1, "e"=>1, "l"=>1} 

However, when we pass the second 'l', we execute

然而,当我们通过第二个“l”时,我们执行

counts['l'] = counts['l'] + 1
  #=>    1 + 1
  #=> 2

and we finish up with

最后

counts #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

The method Enumerable#each_with_object will become a good friend

方法Enumerable#each_with_object将成为好友

This method is used merely to save some steps. It allows us to write:

此方法仅用于保存一些步骤。它允许我们写下:

counts = Hash.new(0)
aw_down.each_char { |c| counts[c] += 1 }

as

作为

counts = aw_down.each_with_object(Hash.new(0)) { |c,h| h[c] += 1 }

and we can also get rid of the line

我们也可以去掉这条直线。

aw_down = aw.downcase 

by writing

通过编写

counts = aw.downcase.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }

This may seem like a small saving, but there are many other situations where the use of each_with_object and other Enumerable class methods permit the chaining of methods, which is extremely useful.

这看起来是一个很小的节省,但是在许多其他情况下,each_with_object和其他可枚举类方法允许对方法进行链接,这是非常有用的。

Decrementing letter counts for letters in the second word

在第二个词中,减缩字母表示字母

Recall

回忆

counts #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

We now execute

我们现在执行

bw_down = bw.downcase
  #=> "helio"
"helio".each_char do |c|
  return false unless counts[c] > 0
  counts[c] -= 1
end

First, 'h' is passed into the block. As counts['h'] #=> 1, we execute counts['h'] -= 1, so now

首先,h被传递到block中。当计数为['h'] #=> 1时,我们执行计数['h'] -= 1,所以现在

counts #=> {"h"=>0, "e"=>1, "l"=>2, "o"=>1}`.

After passing 'e' and 'l' to the block,

将e和l传递给block后,

counts #=> {"h"=>0, "e"=>0, "l"=>1, "o"=>1}

but when we pass 'i', we find

但是当我们通过“i”时,我们就会发现

counts['i'] #=> 0

(i.e., the default value of zero is returned, and we don't want to set counts['i'] to -1) so we return false, having concluded that the two words are not anagrams. (Had the second word been "heeio", we would have returned false when the second 'e' was passed to the block.)

(即。,返回0的默认值,我们不希望将计数['i']设置为-1),因此返回false,因为我们认为这两个词不是字词。(如果第二个单词是“heeio”,那么当第二个“e”传递给block时,我们就会返回false。)

Do we have an anagram?

我们有字谜吗?

Since two two words have the same length, if we are able to process all characters of the second word without returning false, we must end up with

由于两个单词的长度相同,如果我们能够处理第二个单词的所有字符而不返回false,那么我们就必须结束

counts #=> {"h"=>0, "e"=>0, "l"=>0, "o"=>0}

(no need to check!), meaning the two words are anagrams, so in this case we would return true to anagrams.5 Hence, the last line of anagram?.

(不需要检查),意思是这两个字是字谜,所以在这种情况下我们将返回真字谜。因此,最后一行的字谜?

Notes

笔记

1 Under the hood, this is what's happening:

在引擎盖下面,这是正在发生的事情:

enum = c.map
  #=> #<Enumerator: [["hello", "helio"], ["goodbye", "godbye"],
  #                  ["pants", "Spant"], ["baa", "aba"]]:map>

Here we can see what elements the enumerator will pass into the block, but sometimes you need to convert the enumerator to an array to get that information:

在这里,我们可以看到枚举器将向块传递什么元素,但有时需要将枚举器转换为数组,以获得该信息:

enum.to_a
  #=> [["hello", "helio"], ["goodbye", "godbye"],
  #    ["pants", "Spant"], ["baa", "aba"]]

It is actually the method Array#each that passes the elements of enum into the block:

实际上是方法数组#each将enum的元素传递到block中:

enum.each { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
  #=> [0, 0, 1, 1]

2 If we pass [[1,2],3] into a block, and the block variables are written |(a,b),c|, then a=>1, b=>2, c=>3. This is quite handy. Cool, eh?.

2 .如果我们将[[1,2],3]传递到一个块中,块变量被写入|(a,b),c|,那么a=>1, b=>2, c=>3。这是非常方便。很酷,不是吗?。

3

3

h = Hash.new('pig')
h['dog'] = 7 #=> 7
h            #=> {"dog"=>7}
h[0]         #=> "pig"
h['cat']     #=> "pig"
h[{:a=>1}]   #=> "pig"
h            #=> {"dog"=>7}

Note there is a form of Hash#new that takes block, which allows keys not in the hash to be added when they are referenced.

注意,散列#new的一种形式接受块,它允许在引用散列时添加不在散列中的键。

4 Instead of aw_down.each_char we could have written aw_down.chars.each, but aw_down.chars creates an unnecessary intermediate array. each_char, an enumerator, merely passes values as they are required.

4,而不是aw_down。我们可以写aw_down.chars。每一个,但aw_down。chars创建一个不必要的中间数组。enumerator each_char仅仅是在需要的时候传递值。

5 We could return 0 rather than false and 1 rather than true, in which case we could write

5我们可以返回0而不是false, 1而不是true,在这种情况下我们可以写

a.zip(b).map { |aw,bw| anagram?(aw,bw) }

in anagrams, but wouldn't it be clearer to have anagrams return an array whose values are true or false, rather than 0 or 1?

在字谜游戏中,如果一个数组的值为真或假,而不是0或1,它会更清楚吗?

#2


3  

This doesn't have to be rocket science. In fact, so long as you can consistently represent each array, it's a no-brainer:

这并不一定是火箭科学。事实上,只要你能始终如一地表示每个数组,这是显而易见的:

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'spant', 'aba']
c = ['lohel', 'goedboy', 'spant', 'aab']

def anagram_flatten(array)
  array.collect do |word|
    word.chars.sort.join
  end
end

puts anagram_flatten(a) == anagram_flatten(b)
# => false
puts anagram_flatten(a) == anagram_flatten(c)
# => true

I wouldn't worry about partial comparisons when a simple array vs. array comparison is super quick anyway.

当一个简单的数组和数组比较非常快的时候,我不会担心部分比较。

#3


0  

Regarding your code, there are only two things that need to be fixed:

关于你的代码,只有两件事需要修正:

  • the line x = y? do should be if x == y
  • 直线x = y?如果x = y
  • instead of array.find(index) you need to use array[index] (concrete examples: a.find(z) and b.find(z) will become a[z] and b[z], respectively)
  • 你需要使用数组[index]而不是array.find(index)(具体例子:a.find(z)和b.find(z)将分别变成a[z]和b[z]))

Here's your code, with these two fixes applied. It works:

这是您的代码,应用了这两个补丁。工作原理:

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'spant', 'aba']

x = a.length
y = b.length
z = 0

if x == y
    while z < x do
        if a[z].chars.sort.join == b[z].chars.sort.join
            puts 1
        else
            puts 0
        end

        z += 1
    end
end

For a more ruby-idiomatic solution, see tadman's answer.

要得到一个更像橡胶的惯用解决方案,请参见泰德曼的答案。

#4


0  

Alright, I found a solution!

好吧,我找到解决办法了!

for i in 0..a.length-1
  a[i].chars.sort == b[i].chars.sort ? 1 : 0
end

Output

输出

0
0
1
1

#1


3  

[Edit: I've edited my answer to incorporate an efficiency improvement suggested by @raph in a comment on the question (the method anagram? below). That may not be necessary, but I thought it was such a good idea that it should get some exposure. I've also given a detailed explanation, as the OP is new to Ruby, as might be other readers.]

[编辑:我编辑了我的答案,将@raph建议的效率改进融入到对问题的评论中(方法anagram?)下文)。这也许不是必须的,但我认为这是一个很好的主意,它应该得到一些曝光。我也给出了详细的解释,因为OP对Ruby来说是全新的,其他读者可能也是如此。

You might consider doing it as follows.

您可以考虑这样做。

Code

代码

def anagrams(a, b)
  return nil unless a.size == b.size
  a.zip(b).map { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
end

def anagram?(aw, bw)
  return false unless aw.size == bw.size
  counts = aw.downcase.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
  bw.downcase.each_char do |c|
    return false unless counts[c] > 0
    counts[c] -= 1
  end
  true
end

Example

例子

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'Spant', 'aba']
anagrams(a, b)
  #=> [0, 0, 1, 1]

Explanation

解释

anagrams method

字谜方法

For the example above,

对于上面的示例,

a.size #=> 4
b.size #=> 4

so we don't return nil in the first line of anagrams.

所以我们不会在字谜的第一行返回nil。

Next,

接下来,

c = a.zip(b)
  #=> [["hello", "helio"], ["goodbye", "godbye"],
  #    ["pants", "Spant"], ["baa", "aba"]]

Assuming for a moment that anagram? works as desired:

假设这是一个字谜?是想要的:

c.map { |e| anagram?(e.first, e.last) ? 1 : 0 }
  #=> [0, 0, 1, 1]

Enumerable#map passes each element of c (a two-element array) into the block.1. It is clearer, however, to decompose (or "disambiguate") those arrays and assign each of the two words they comprise to a block variable2:

Enumerable#map将c(一个双元素数组)中的每个元素都传递到block.1中。但是,更清楚的是,分解(或“消除歧义”)这些数组,并将它们组成的两个单词中的每一个赋值给block variable2:

c.map { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
  #=> [0, 0, 1, 1]

The first element passed in is ["hello", "helio"], so

传入的第一个元素是["hello", "helio"]。

aw => "hello"
bw #=> "helio"

and we execute

我们执行

anagram?("hello", "helio") ? 1 : 0
  #=> 0

which is shorthand for

这是缩写

if anagram?("hello", "helio")
  1
else
  0
end
  #=> 0

anagram? method

回文构词法吗?方法

So now let's move on to anagram?, with

现在我们来看看字母组合?,

aw = "hello"
bw = "helio"

Since

aw.size == bw.size #=> true

we don't return.

我们不回来了。

Count frequency of letters in the first word

计算第一个单词中字母的频率

Let me now write the next few lines of anagram? slightly differently:

下面几行字母组合?略有不同:

counts = Hash.new(0)
  #=> {}
aw_down = aw.downcase 
  #=> "hello"
aw_down.each_char { |c| counts[c] += 1 }
  #=> "hello"
counts
  #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

(The last line is there just to show the value of the hash.)

(最后一行只是显示哈希值)

In the first line we create a hash counts with a default value of zero. All this means is that if counts does not contain the key k, counts[k] will return the default value. Very important: doing so does not change the hash!3

在第一行中,我们创建一个带有默认值为0的散列计数。所有这一切意味着如果计数不包含键k,计数[k]将返回默认值。非常重要:这样做不会改变散列

String#each_char4 passes each character of "hello" into the block and assigns it to the block variable c. Initially, c='h' and h={}. We then execute

字符串#each_char4将“hello”的每个字符传递到块中,并将其分配给块变量c.最初,c='h'和h={}。然后,我们执行

counts['h'] += 1

which is shorthand for

这是缩写

counts['h'] = counts['h'] + 1

Since counts does not yet have a key 'h', counts['h'] on the right returns the default value:

由于count还没有键h,所以右边的counts[h]会返回默认值:

counts['h'] = 0 + 1 #=> 1
counts #=> {"h"=>1}

Similarly, after 'e' and the first 'l' are passed to the block, we have:

类似地,在将'e'和第一个'l'传递给block之后,我们有:

counts #=> {"h"=>1, "e"=>1, "l"=>1} 

However, when we pass the second 'l', we execute

然而,当我们通过第二个“l”时,我们执行

counts['l'] = counts['l'] + 1
  #=>    1 + 1
  #=> 2

and we finish up with

最后

counts #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

The method Enumerable#each_with_object will become a good friend

方法Enumerable#each_with_object将成为好友

This method is used merely to save some steps. It allows us to write:

此方法仅用于保存一些步骤。它允许我们写下:

counts = Hash.new(0)
aw_down.each_char { |c| counts[c] += 1 }

as

作为

counts = aw_down.each_with_object(Hash.new(0)) { |c,h| h[c] += 1 }

and we can also get rid of the line

我们也可以去掉这条直线。

aw_down = aw.downcase 

by writing

通过编写

counts = aw.downcase.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }

This may seem like a small saving, but there are many other situations where the use of each_with_object and other Enumerable class methods permit the chaining of methods, which is extremely useful.

这看起来是一个很小的节省,但是在许多其他情况下,each_with_object和其他可枚举类方法允许对方法进行链接,这是非常有用的。

Decrementing letter counts for letters in the second word

在第二个词中,减缩字母表示字母

Recall

回忆

counts #=> {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

We now execute

我们现在执行

bw_down = bw.downcase
  #=> "helio"
"helio".each_char do |c|
  return false unless counts[c] > 0
  counts[c] -= 1
end

First, 'h' is passed into the block. As counts['h'] #=> 1, we execute counts['h'] -= 1, so now

首先,h被传递到block中。当计数为['h'] #=> 1时,我们执行计数['h'] -= 1,所以现在

counts #=> {"h"=>0, "e"=>1, "l"=>2, "o"=>1}`.

After passing 'e' and 'l' to the block,

将e和l传递给block后,

counts #=> {"h"=>0, "e"=>0, "l"=>1, "o"=>1}

but when we pass 'i', we find

但是当我们通过“i”时,我们就会发现

counts['i'] #=> 0

(i.e., the default value of zero is returned, and we don't want to set counts['i'] to -1) so we return false, having concluded that the two words are not anagrams. (Had the second word been "heeio", we would have returned false when the second 'e' was passed to the block.)

(即。,返回0的默认值,我们不希望将计数['i']设置为-1),因此返回false,因为我们认为这两个词不是字词。(如果第二个单词是“heeio”,那么当第二个“e”传递给block时,我们就会返回false。)

Do we have an anagram?

我们有字谜吗?

Since two two words have the same length, if we are able to process all characters of the second word without returning false, we must end up with

由于两个单词的长度相同,如果我们能够处理第二个单词的所有字符而不返回false,那么我们就必须结束

counts #=> {"h"=>0, "e"=>0, "l"=>0, "o"=>0}

(no need to check!), meaning the two words are anagrams, so in this case we would return true to anagrams.5 Hence, the last line of anagram?.

(不需要检查),意思是这两个字是字谜,所以在这种情况下我们将返回真字谜。因此,最后一行的字谜?

Notes

笔记

1 Under the hood, this is what's happening:

在引擎盖下面,这是正在发生的事情:

enum = c.map
  #=> #<Enumerator: [["hello", "helio"], ["goodbye", "godbye"],
  #                  ["pants", "Spant"], ["baa", "aba"]]:map>

Here we can see what elements the enumerator will pass into the block, but sometimes you need to convert the enumerator to an array to get that information:

在这里,我们可以看到枚举器将向块传递什么元素,但有时需要将枚举器转换为数组,以获得该信息:

enum.to_a
  #=> [["hello", "helio"], ["goodbye", "godbye"],
  #    ["pants", "Spant"], ["baa", "aba"]]

It is actually the method Array#each that passes the elements of enum into the block:

实际上是方法数组#each将enum的元素传递到block中:

enum.each { |aw,bw| anagram?(aw,bw) ? 1 : 0 }
  #=> [0, 0, 1, 1]

2 If we pass [[1,2],3] into a block, and the block variables are written |(a,b),c|, then a=>1, b=>2, c=>3. This is quite handy. Cool, eh?.

2 .如果我们将[[1,2],3]传递到一个块中,块变量被写入|(a,b),c|,那么a=>1, b=>2, c=>3。这是非常方便。很酷,不是吗?。

3

3

h = Hash.new('pig')
h['dog'] = 7 #=> 7
h            #=> {"dog"=>7}
h[0]         #=> "pig"
h['cat']     #=> "pig"
h[{:a=>1}]   #=> "pig"
h            #=> {"dog"=>7}

Note there is a form of Hash#new that takes block, which allows keys not in the hash to be added when they are referenced.

注意,散列#new的一种形式接受块,它允许在引用散列时添加不在散列中的键。

4 Instead of aw_down.each_char we could have written aw_down.chars.each, but aw_down.chars creates an unnecessary intermediate array. each_char, an enumerator, merely passes values as they are required.

4,而不是aw_down。我们可以写aw_down.chars。每一个,但aw_down。chars创建一个不必要的中间数组。enumerator each_char仅仅是在需要的时候传递值。

5 We could return 0 rather than false and 1 rather than true, in which case we could write

5我们可以返回0而不是false, 1而不是true,在这种情况下我们可以写

a.zip(b).map { |aw,bw| anagram?(aw,bw) }

in anagrams, but wouldn't it be clearer to have anagrams return an array whose values are true or false, rather than 0 or 1?

在字谜游戏中,如果一个数组的值为真或假,而不是0或1,它会更清楚吗?

#2


3  

This doesn't have to be rocket science. In fact, so long as you can consistently represent each array, it's a no-brainer:

这并不一定是火箭科学。事实上,只要你能始终如一地表示每个数组,这是显而易见的:

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'spant', 'aba']
c = ['lohel', 'goedboy', 'spant', 'aab']

def anagram_flatten(array)
  array.collect do |word|
    word.chars.sort.join
  end
end

puts anagram_flatten(a) == anagram_flatten(b)
# => false
puts anagram_flatten(a) == anagram_flatten(c)
# => true

I wouldn't worry about partial comparisons when a simple array vs. array comparison is super quick anyway.

当一个简单的数组和数组比较非常快的时候,我不会担心部分比较。

#3


0  

Regarding your code, there are only two things that need to be fixed:

关于你的代码,只有两件事需要修正:

  • the line x = y? do should be if x == y
  • 直线x = y?如果x = y
  • instead of array.find(index) you need to use array[index] (concrete examples: a.find(z) and b.find(z) will become a[z] and b[z], respectively)
  • 你需要使用数组[index]而不是array.find(index)(具体例子:a.find(z)和b.find(z)将分别变成a[z]和b[z]))

Here's your code, with these two fixes applied. It works:

这是您的代码,应用了这两个补丁。工作原理:

a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'spant', 'aba']

x = a.length
y = b.length
z = 0

if x == y
    while z < x do
        if a[z].chars.sort.join == b[z].chars.sort.join
            puts 1
        else
            puts 0
        end

        z += 1
    end
end

For a more ruby-idiomatic solution, see tadman's answer.

要得到一个更像橡胶的惯用解决方案,请参见泰德曼的答案。

#4


0  

Alright, I found a solution!

好吧,我找到解决办法了!

for i in 0..a.length-1
  a[i].chars.sort == b[i].chars.sort ? 1 : 0
end

Output

输出

0
0
1
1