在Ruby中交换字符串中的字母

时间:2015-07-09 13:46:44

标签: ruby

我需要使用Ruby和以下规则交换字符串(DNA链)中的字母:

  • 'A'已被'T'
  • 取代
  • 'T'已被'A'
  • 取代
  • 'C'已被'G'
  • 取代
  • 'G'已被'C'
  • 取代

例如,'ACGTA'应该变为'TGCAT'

我只有这么远:

def DNA_strand(dna)    
  dna.tr!('A', 'T')    
end

1 个答案:

答案 0 :(得分:6)

你很亲密:

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

请参阅ruby-doc.org on tr

  

返回str的副本,其中from_str中的字符替换为to_str   tr!中的相应字符。

如果您想要就地修改字符串,请以相同的方式使用protected void btnAddToCart_Click(object sender, EventArgs e) { string ProductID = Convert.ToInt16((((Button)sender).CommandArgument)).ToString(); string ProductQuantity = "1"; DataListItem currentItem = (sender as Button).NamingContainer as DataListItem; Label lblAvailableStock = currentItem.FindControl("lblAvailableStock") as Label; if (Session["MyCart"] != null) { DataTable dt = (DataTable)Session["MyCart"]; var checkProduct = dt.AsEnumerable().Where(r => r.Field<string>("ProductID") == ProductID); // check whether product is already added or not if (checkProduct.Count() == 0) { string query = "select * from Products where ProductID = " + ProductID + ""; DataTable dtProducts = GetData(query); DataRow dr = dt.NewRow(); dr["ProductID"] = ProductID; dr["Name"] = Convert.ToString(dtProducts.Rows[0]["Name"]); dr["Description"] = Convert.ToString(dtProducts.Rows[0]["Description"]); dr["Price"] = Convert.ToString(dtProducts.Rows[0]["Price"]); dr["ImageUrl"] = Convert.ToString(dtProducts.Rows[0]["ImageUrl"]); dr["ProductQuantity"] = ProductQuantity; dr["AvailableStock"] = lblAvailableStock.Text; dt.Rows.Add(dr); Session["MyCart"] = dt; btnIslandGas.Text = dt.Rows.Count.ToString(); } else { if (checkProduct.Count() != 0) { var ProductRowToBeDeleted = dt.Select("ProductID =" + ProductID); foreach (var row in ProductRowToBeDeleted) { row.Delete(); btnIslandGas.Text = dt.Rows.Count.ToString(); } } } } else { string query = "select * from Products where ProductID = " + ProductID + ""; DataTable dtProducts = GetData(query); DataTable dt = new DataTable(); //storing all of the records dt.Columns.Add("ProductID", typeof(string)); // adding the columns dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Description", typeof(string)); dt.Columns.Add("Price", typeof(string)); dt.Columns.Add("ImageUrl", typeof(string)); dt.Columns.Add("ProductQuantity", typeof(string)); dt.Columns.Add("AvailableStock", typeof(string)); DataRow dr = dt.NewRow(); //adding the rows dr["ProductID"] = ProductID; dr["Name"] = Convert.ToString(dtProducts.Rows[0]["Name"]); dr["Description"] = Convert.ToString(dtProducts.Rows[0]["Description"]); dr["Price"] = Convert.ToString(dtProducts.Rows[0]["Price"]); dr["ImageUrl"] = Convert.ToString(dtProducts.Rows[0]["ImageUrl"]); dr["ProductQuantity"] = ProductQuantity; dr["AvailableStock"] = lblAvailableStock.Text; dt.Rows.Add(dr); //adding the data row in the data table. Session["MyCart"] = dt; //asigning the datatable in the session. btnIslandGas.Text = dt.Rows.Count.ToString(); } HighLightCartProducts(); }