Ruby 这段 rust 代码用 ruby 会如何,感觉这基本的函数式写法没区别吧

zzz6519003 · 2024年02月22日 · 最后由 zzz6519003 回复于 2024年02月23日 · 433 次阅读
use std::cmp::Ordering;

use sha2::{Digest, Sha256};

const TWITTER_ACCOUNTS: &[&str] = &["userX", "userY", "userZ"];
const SEED: u16 = 666;

fn main() {
    let target_account = TWITTER_ACCOUNTS
        .iter()
        .map(|account| {
            let mut hasher = Sha256::new();
            hasher.update(account.as_bytes());
            let digest = hasher.finalize();

            let mut magic_number = (digest[0] as u16) << 8;
            magic_number |= digest[1] as u16;
            magic_number = magic_number % 999;

            let distance = magic_number.abs_diff(SEED);

            (*account, distance)
        })
        .min_by(|x, y| match x.1.cmp(&y.1) {
            Ordering::Equal => x.0.cmp(y.0),
            res @ _ => res,
        })
        .map(|(account, _)| account)
        .expect("should returns a value");
    println!("{target_account}");
}

require 'digest'

TWITTER_ACCOUNTS = ["userX", "userY", "userZ"]
SEED = 666

def main
  target_account = TWITTER_ACCOUNTS.map do |account|
    digest = Digest::SHA256.hexdigest(account)
    # 将16进制字符串的前4个字符转换为16进制数值后再转为整数
    magic_number = digest[0..3].to_i(16) % 999
    distance = (magic_number - SEED).abs

    [account, distance]
  end.min_by { |account, distance| distance }

  puts target_account[0]
end

main()

EvanYa 回复

果然看起来更优雅~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号