0

I have an array like this.

@arr  =  ["Ac", "Ba", "Ca", "Dd", "aC", "bD", "cA", "dD"] 

I want to swap the letter if the first one is a capital. In this case, Ac becomes cA, Ba -> aB etc. This becomes like this.

@arr = ["cA", "aB", "aC", "dD", "aC", "bD", "cA", "dD"] 

Then I want to find the same item. In this case there are two, cA and dD.

@newarr = ["cA", "dD"]

This is what I have got so far:

@firstarr = @arr.map{|item| 
      if item[0] =~ /[A-Z]/
        item = item[1]+item[0]
      else
        itme = item
      end
    }

This gives

@firstarr = ["cA", "aB", "aC", "dD", "aC", "bD", "cA", "dD"]
halfer
  • 19,824
  • 17
  • 99
  • 186
shin
  • 31,901
  • 69
  • 184
  • 271
  • And what have you tried? – coreyward Apr 06 '14 at 22:15
  • possible duplicate of [Ruby: How to find and return a duplicate value in array?](http://stackoverflow.com/questions/8921999/ruby-how-to-find-and-return-a-duplicate-value-in-array) – morten.c Apr 06 '14 at 22:17

3 Answers3

1

For your reversing criteria:

foo = @arr.map do |x|
  (x[0].downcase!).nil? ? x : x.reverse
end
# => ["cA", "aB", "aC", "dD", "aC", "bD", "cA", "dD"]

downcase! returns nil if the receiver is already in downcase, using this, above code checks if x[0] can be downcase-d; if yes, that means the first character is in uppercase and it reverse the word, else it returns the same word.

For duplication criteria:

foo.select { |x| foo.count(x) > 1 }.uniq
# => ["cA", "aC", "dD"]
kiddorails
  • 12,961
  • 2
  • 32
  • 41
1
arr = ["Ac", "Ba", "Ca", "Dd", "aC", "bD", "cA", "dD"]
arr.each_with_object(Hash.new(0)) { |x,h| 
  (x !~ /[a-z][A-Z]/) ? h[x.reverse] += 1 : h[x] += 1 }.select { |k,v| v > 1 }.keys
#=> ["cA", "aC", "dD"]
bjhaid
  • 9,592
  • 2
  • 37
  • 47
1

An approach intended to read well:

Code

arr = ["Ac", "Ba", "Ca", "Dd", "aC", "bD", "cA", "dD"] 

new_arr = arr.map { |str| str[0] == str[0].upcase ? str.reverse : str }
  #=> ["cA", "aB", "aC", "dD", "aC", "bD", "cA", "dD"]

new_arr.group_by { |e| e }
       .select { |_,v| v.size > 1 }
       .keys
  #=> ["cA", "aC", "dD"]  

Explanation

The calculation of new_arr is straightforward.

new_arr = ["cA", "aB", "aC", "dD", "aC", "bD", "cA", "dD"]

a = new_arr.group_by { |e| e }
  #=> { "cA"=>["cA", "cA"], "aB"=>["aB"], "aC"=>["aC", "aC"],
  #     "dD"=>["dD", "dD"], "bD"=>["bD"] }

b = a.select { |_,v| v.size > 1 }
  #=> { "cA"=>["cA", "cA"], "aC"=>["aC", "aC"], "dD"=>["dD", "dD"] }

b.keys
  #=> ["cA", "aC", "dD"]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100