{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreif2xzxs26cbt6iak6zky7z2ulgz774kcckqavxfg7hxdqcsjlcep4",
"uri": "at://did:plc:kfvfl6lsmxg64yzszmfotdq2/app.bsky.feed.post/3mnbjey2wme62"
},
"path": "/t/ruby-talk-444825-pattern-matching-as-string-passing-patters-to-functions/76779#post_2",
"publishedAt": "2026-06-01T04:28:30.000Z",
"site": "https://rubytalk.org",
"tags": [
"(click for more details)"
],
"textContent": "im lazy. straight from copilot\n\nPattern Matching with String Keys\nBy default, Ruby’s hash pattern matching expects symbol keys. That’s why\nyour example works when you load YAML with symbolize_names: true. If you\nkeep string keys, you need to explicitly match them:\n\nruby\ny = YAML.safe_load(yaml_data) # no symbolize_names\n\ny[\"cards_on_hand\"].each do |a_card|\ncase a_card\nin { \"suite\" => String => captured_suite, \"value\" => \"king\" }\nputs \"you have a king on your hand and its suite is #{captured_suite}\"\nelse\nputs \"a card of no interest #{a_card.inspect}\"\nend\nend\nNotice the difference:\n\nsuite: → matches a symbol key\n\n\"suite\" => → matches a string key\n\nSo:\n\nUse symbolize_names: true if you want to work with symbols.\n\nOr match with \"key\" => if you want to keep string keys.\n\nPassing Patterns into Functions\nPatterns in Ruby are objects (they’re part of the language syntax). You\ncan’t directly “store” a pattern as a variable, but you can wrap matching\nlogic in a method and use case ... in inside it.\n\nExample:\n\nruby\ndef match_card(card, pattern)\ncase card\nin pattern\nyield $~ if block_given? # or just return true\nelse\nnil\nend\nend\n\npattern = { suite: String => suite, value: \"king\" }\n\ny[:cards_on_hand].each do |card|\nmatch_card(card, pattern) do\nputs \"Captured suite: #{suite}\"\nend\nend\nAnother approach is to use procs/lambdas for reusable matching logic:\n\nruby\nking_pattern = ->(card) {\ncase card\nin { suite: String => s, value: \"king\" }\ns\nelse\nnil\nend\n}\n\ny[:cards_on_hand].each do |card|\nif (suite = king_pattern.call(card))\nputs \"You have a king of #{suite}\"\nend\nend\nThis way, you can pass around reusable matchers like any other object.\n\nKey Takeaways\nUse symbol: for symbol keys, \"string\" => for string keys.\n\nWrap patterns in methods or lambdas to pass them around.\n\nCaptures (=> var) work fine inside those reusable matchers.\n\n··· (click for more details)",
"title": "[ruby-talk:444825] Pattern matching as String, passing patters to functions"
}