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"]
2

3 Answers 3

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"]
Sign up to request clarification or add additional context in comments.

Comments

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"]

Comments

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.