External Publication
Visit Post

[ruby-talk:444825] Pattern matching as String, passing patters to functions

Ruby Mailing List Mirror [Unofficial] May 26, 2026
Source

Hi Rubyists,

is this the place to ask beginner questions?

I am confused about pattern matching. It only seems to work when the key is of type symbol. How would I apply pattern matching to string keys?

Example

require "yaml"

yaml_data=" cards_on_hand:

  • suite: hearts value: '9'
  • suite: hearts value: 'king'
  • suite: diamonds value: 'king' "

y=YAML.safe_load(yaml_data, symbolize_names: true) puts y.inspect

y[:cards_on_hand].each do |a_card| case a_card in { suite: String => captured_suite, value: 'king' } puts "you have a king on your hand and its suite is #{captured_suite}" else puts "a card of no interest #{a_card.inspect}" end end

{cards_on_hand: [{suit: "hearts", value: "9"}, {suit: "hearts", value: "king"}, {suit: "diamonds", value: "king"}]}

a card of no interest {suite: "hearts", value: "9"} you have a king on your hand and its suite is hearts you have a king on your hand and its suite is diamonds

Second question:

Since everything in Ruby is an object, how do I pass patterns into a function? Even more specific, how do I handle capture when passing to a function?

Cheers, Marcus

··· (click for more details)

Discussion in the ATmosphere

Loading comments...