我试图从哈希中获取具有相同值的所有键,并将它们作为单独的条目放入数组中。我有这行代码,但它将所有内容作为单个条目发送:
@highest_wf_words << h.select {|k, v| v == val}.keys
任何人都可以建议如何分开键,所以我最终得到[[“a”],[“b”],[“c”]]而不是[[“a”,“b”,“c” ]],
答案 0 :(得分:2)
也许这个?
h.select {|k, v| v == val}.keys.each {|k| @highest_wf_words << [k]}
或者这个:
@highest_wf_words.concat(h.select {|k, v| v == val}.keys.map {|k| [k]})
答案 1 :(得分:2)
我建议你构造一个哈希而不是一个数组。
type
TForm16 = class(TForm)
Image1 : TImage; //Load SomeFile.png
StatusBar1: TStatusBar;
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
PNGImage1 : TPNGImage; //Load SomeFile.png into this as well
public
{ Public declarations }
end;
var
Form16: TForm16;
implementation
{$R *.dfm}
procedure TForm16.FormCreate( Sender : TObject );
begin
PNGImage1 := TPNGImage.Create();
PNGImage1.Assign( Image1.Picture ); //Assign SomeFile.png
end;
procedure TForm16.FormDestroy( Sender : TObject );
begin
PNGImage1.Free();
end;
procedure TForm16.Image1MouseMove( Sender : TObject; Shift : ShiftState; X, Y : Integer );
var
Alpha: PByte;
begin
Alpha := @PNGImage1.AlphaScanline[Y]^[X];
if( Alpha^ > 0 ) then
Image1.Cursor := crDrag
else
Image1.Cursor := crDefault;
Statusbar1.Panels[0].Text := IntToStr( Alpha^ );
end;
end.
这回答了问题标题提出的问题。
答案 2 :(得分:0)
甚至更好,但更简单:
h.select { |k,v| v == h.values.max }.keys
例如,
h = { "a" => 1, "b" => 2, "c" => 2 }
# implement the above solution
h.select { |k,v| v == h.values.max }.keys
#=> ["b", "c"]
希望这就是您想要的! :)