Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping letters in a string in Ruby

Tags:

ruby

I need to swap letters in a string (DNA strand) using Ruby and the following rules:

  • 'A' is replaced by 'T'
  • 'T' is replaced by 'A'
  • 'C' is replaced by 'G'
  • 'G' is replaced by 'C'

For example, 'ACGTA' should become 'TGCAT'.

I have only got this far:

def DNA_strand(dna)    
  dna.tr!('A', 'T')    
end
like image 819
KVyas Avatar asked Apr 01 '26 04:04

KVyas


1 Answers

You were quite close:

dna.tr('ATCG', 'TAGC')   # => "TGCAT"

See ruby-doc.org on tr:

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str.

Use tr! the same way if you want to modify your string in-place.

like image 156
undur_gongor Avatar answered Apr 02 '26 20:04

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!