I am trying to make a ButtonBar
that prints the name of the card in question.
What I have so far is as follows:
myHand = {{1, "Spades"}, {4, "Hearts"}, {5, "Clubs"}, {8,
"Spades"}, {9, "Hearts"}, {9, "Spades"}, {11, "Spades"}};
ButtonBar[Table[
ToString[myHand[[i, 1]]] <> " of " <> ToString[myHand[[i, 2]]] :>
Print[myHand[[i]]],
{i, Length@myHand}]
]
However, instead of working as expected and printing out the name of the card in question, it always prints out {9, Hearts}
. When I looked into the FullForm
for this it made sense why:
ButtonBar[List[RuleDelayed["1 of Spades", Print[Part[myHand, i]]],
RuleDelayed["4 of Hearts", Print[Part[myHand, i]]],
RuleDelayed["5 of Clubs", Print[Part[myHand, i]]],
RuleDelayed["8 of Spades", Print[Part[myHand, i]]],
RuleDelayed["9 of Hearts", Print[Part[myHand, i]]],
RuleDelayed["9 of Spades", Print[Part[myHand, i]]],
RuleDelayed["11 of Spades", Print[Part[myHand, i]]]]]
The rule is to print out i
, not the actual number. How can I remedy this so that my Table
generates a list of actual rules without holding the i
s back from being evaluated in the Table
?
RuleDelayed
has an attributeHoldRest
you have tu useEvaluate
(not always possible) or injecti
withWith
likeWith[{i = i}, "string":>list[[i]]]
$\endgroup$ButtonBar[Table[ With[{i = i}, ToString[myHand[[i, 1]]] <> " of " <> ToString[myHand[[i, 2]]] :> Print[myHand[[i]]]], {i, Length@myHand}]]
$\endgroup$ButtonBar[(Row[ToString /@ #, " of "] :> Print[#]) & /@ myHand ]
works as you need? $\endgroup$ButtonBar[Table[Row[ToString /@ j, " of "] :> Print[j] /. j -> i, {i, myHand}]]
$\endgroup$Range[Length[myHand]] /. i_Integer :> (ToString[myHand[[i, 1]]] <> " of " <> ToString[myHand[[i, 2]]]) :> Print[myHand[[i]]]
. $\endgroup$