简体   繁体   中英

How to compare array with keys in a hash in ruby?

I'm building a simple encrypter to encrypt a string in ruby.

cipher = {"a" => "6", "b" => "$", "c" => "X"...}
key_word = "secret"
key_word.split(//)
=> ["s", "e", "c", "r", "e", "t"]

How can I compare the key_word characters with the keys in my cipher hash and return them?

您可以使用Rexexp.unionString#gsub的哈希参数版本来实现:

encrypted = key_word.gsub(Regexp.union(cipher.keys), cipher)

One form of String#gsub takes a hash as an argument:

encrypted = key_word.gsub(/./, cipher)

So just match each character and replace it with its value in cipher . If cipher does not have a key equal to the character, the character is left unchanged.

You could do something like this:

cipher = {"a" => "6", "b" => "$", "c" => "X"}

'abc'.tr(cipher.keys.join, cipher.values.join)
#=> "6$X"

or with split and join (what might be much slower):

'abc'.each_char.map { |char| cipher[char] }.join
#=> "6$X"

就这么简单:

ciper.values_at(*key_word.split(//)).join

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM