On Wed, Jun 6, 2012 at 9:09 AM, RR TT <[email protected]> wrote:
> Hello, I have some sample delphi codes which I want to convert to Ruby
> for test purposes, anyone can help me:

These are all one liners.  Btw, I would assume Delphi solutions could
be shorter as well.

> 1. Replace single quotes with double quotes:
>
> function ReplaceSingleQuote(AText: String): String;
> begin
>    Result := '';
>    if Length(AText) = 0 then
>        Exit;
>    Result := StringReplace(AText, '''', '''''', [rfReplaceAll]);
> end;

result = a_text.gsub /'/, "''"

> 2. ANSI Split Strings:
>
> function  AnsiSplitStrings(const str: string;const separator: string =
> ',';Strings: TStrings = nil): TStrings;
> var
>   n: integer;
>   p, q, s: PChar;
>   item,sString: string;
> begin
>     if Strings = nil then
>        Result := TStringList.Create
>     else
>         Result := Strings;
>     if str='' then exit;
>     if str[Length(str)] = separator then
>        sString := AnsiLeftStr(str,Length(str)-1)
>     else
>         sString := str;
>
>     try
>        p := PChar(sString);
>        s := PChar(separator);
>        n := Length(separator);
>        repeat
>              q := AnsiStrPos(p, s);
>              if q = nil then q := AnsiStrScan(p, #0);
>              SetString(item, p, q - p);
>              Result.Add(item);
>              p := q + n;
>        until q^ = #0;
>     except
>           item := '';
>           if Strings = nil then Result.Free;
>           raise;
>     end;
> end;

result = str.split(Regexp.new(Regexp.escape(separator)))

> 3. Check phone format:
>
> function IsPhoneFormatCorrect(sPhoneNo: string): Boolean;
> var iPos:integer;
> begin
>     if Length(sPhoneNo) > 0 then
>        begin
>             iPos := 1;
>             Result := (Length(sPhoneNo) > 3) and (sPhoneNo[iPos] = '+')
> and (AnsiPos('(',sPhoneNo) > 1) and (AnsiPos(')',sPhoneNo) >
> (AnsiPos('(',sPhoneNo)+1));
>        end
>     else
>         Result := true;
> end;

result = /\A(?:\+[^)]*\([^()].*\).*)?\z/ =~ s_phone_no

Funny thing is: you do not require numbers in the phone _number_.
Also, the empty string is a phone number which seems rather odd to me.
 Even if an empty string is OK I would make the function only check
for properly formatted phone numbers and have the check for empty
string outside. That is much more modular and can be better reused.

Cheers

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to